首页 > 编程语言 >Python 使用wmi获取远程端电脑的磁盘使用情况

Python 使用wmi获取远程端电脑的磁盘使用情况

时间:2022-08-30 12:48:22浏览次数:44  
标签:Ret Python IP Pwd Logical wmi GB 磁盘 Disk

安装wmi包

pip install wmi

说明:执行上面命令会自动安装依赖包pywin32

代码演示

import json as JSON
import re
import paramiko
import suds
from suds.wsse import *
import wmi


class WindowsDisListen():
    """Windows系统"""

    def getSpaceInfo(self, P_IP, P_User, P_Pwd):
        # GB = 1024 ** 3
        # total_b, used_b, free_b = shutil.disk_usage('C:')  # 查看磁盘的使用情况
        # print('总的磁盘空间: {:.2f}GB '.format(total_b / GB))
        # print('已经使用的 : {:.2f}GB '.format(used_b / GB))
        # print('未使用的 : {:.2f}GB '.format(free_b / GB))

        IP, User, Pwd = P_IP, P_User, P_Pwd
        # 初始化返回数据格式
        Ret = {"code": "0", "msg": "OK", "data": []}

        # 连接服务器
        try:
            Win = wmi.WMI(computer=IP, user=User, password=Pwd)
        except Exception as e:
            Ret["code"] = "-1"
            Ret["msg"] = "目标服务器" + IP + "连接失败!" + str(e)
            return JSON.dumps(Ret, ensure_ascii=False)

        # 获取硬盘使用百分情况
        GB = 1024 ** 3
        Data = []
        for Physical_Disk in Win.Win32_DiskDrive():
            for Partition in Physical_Disk.associators("Win32_DiskDriveToDiskPartition"):
                for Logical_Disk in Partition.associators("Win32_LogicalDiskToPartition"):
                    TmpDict = {}
                    TmpDict["盘符"] = Logical_Disk.Caption
                    TmpDict["总量"] = format(int(Logical_Disk.Size) / GB, '.2f')
                    TmpDict["使用量"] = format((int(Logical_Disk.Size) - int(Logical_Disk.FreeSpace)) / GB, '.2f')
                    TmpDict["空闲量"] = format(int(Logical_Disk.FreeSpace) / GB, '.2f')
                    TmpDict["使用率"] = format(int(100.0 * (int(Logical_Disk.Size) - int(Logical_Disk.FreeSpace)) / int(Logical_Disk.Size)), '.2f') + "%"
                    Data.append(TmpDict)

        Ret["data"] = Data
        return JSON.dumps(Ret, ensure_ascii=False)


class Msg():
    """短信接口"""

    @classmethod
    def sendListenMsg(cls, Contetn, Phone=""):
        """调用短信平台,发送短信"""
        Wsdl_Url = "http://100.169.130.50:57772/dthealth/web/wcw.soap.ShortMsg.cls?WSDL=1&CacheUserName=dhwebservice&CachePassword=dhwebservice&CacheNoRedirect=1"
        Soap = suds.Client(Wsdl_Url)
        # 设置Token安全登录验证
        security = Security()
        token = UsernameToken('dhwebservice', 'dhwebservice')
        security.tokens.append(token)
        Soap.set_options(wsse=security)

        # 接收电话(多个手机号用","拼接)
        if Phone=="": Phone = "180***65,156***67,176***69"        
        # 调用接口
        Ret = Soap.service.sendMsg(Contetn, Phone)

        return Ret


def runWindows(P_IP, P_User, P_Pwd):
    """执行Windows监测程序并发送预警短信"""

    IP, User, Pwd = P_IP, P_User, P_Pwd
    WinDis = WindowsDisListen()
    DataList = JSON.loads(WinDis.getSpaceInfo(IP, User, Pwd))
    NeedSendCont = []
    for Item in DataList["data"]:
        for Name, Value in Item.items():
            if Name == "使用率" and float(Value.strip("%")) >= 90:
                NeedSendCont.append("【" + Item["盘符"] + "盘】空间使用率为【" + Item["使用率"] + "】,空间不足。")

    # 短息内容
    MsgContent = "服务器监测预警:服务器" + IP + "".join(NeedSendCont) + "请及时报给信息科处理!"

    # 发短信
    MsgRet = ""
    if len(NeedSendCont): MsgRet = Msg.sendListenMsg(MsgContent)
    if MsgRet == "1":
        MsgRet = "发送短信成功。"
    else:
        MsgRet = "未发送短信,或发送短信失败。"
    print(MsgRet + "短信内容为:" + MsgContent)


if __name__ == '__main__':
    # 程序入口
    runWindows("100.169.130.110", "Hisweb110", "Hisweb#2019#11")
    runWindows("100.169.130.120", "Hisweb120", "Hisweb#2019#12")
 

 

标签:Ret,Python,IP,Pwd,Logical,wmi,GB,磁盘,Disk
From: https://www.cnblogs.com/wcwnina/p/16638855.html

相关文章

  • Python基础语法知识
    3、python基础语法知识3.1变量1.什么是变量?可以变化的量2.为什么要有变量?程序去执行一种状态,并且是可以变化的1.变量的使用原则:先定义,后使用name='hello'#定义pr......
  • Python基础
    Python1、基础知识1.1编程语言什么是语言?为什么要有编程语言?什么是编程?为什么要编程?编程语言的本质就是一门语言,是人与计算机沟通的一种介质。人与人之间......
  • Python--自动将文件分类归入文件夹
    转载:(63条消息)Python--自动将文件分类归入文件夹_JavaNewMans的博客-CSDN博客_python文件夹分类   ##推荐(63条消息)【python】将不同后缀的文件分开到不同文......
  • 220830-linux磁盘系统初识
    linux中,每一个设备都会被当做一个文件来看待。在linux中,所有的硬件设备文件都会在/dev这个目录下。而SATA接口的硬盘文件名称会被命名为/dev/sd[a-d]。分区的命名:Windows......
  • python实现常量类
    const有什么好处?最直接的好处是,防止被二次修改导致整个程序崩掉!第一种方法,使用enum来定义变量,防止串改.fromenumimportEnum,unique#若要不能定义相同的成员值......
  • Python使用gdb进行debug的方法
    准备工作:1、必须安装gdb,一般系统默认安装过了,未安装的根据系统使用不同命令安装,比如yuminstallgdb,也可以用rpm命令进行安装2、必须有一个携带符号表的Python,版本与要......
  • python print居中-靠右-靠左输出
    1 居中输出   需要使用center函数使用center函数,需要str类型的数据。width参数:长度,需要填一个int类型的参数fillchar参数:两边填充的字符,需要一个str类型的参数(可以......
  • Python入门系列(五)一篇搞懂python语句
    If语句elif关键字是pythons表示“如果前面的条件不为真,那么试试这个条件”。Theelsekeywordcatchesanythingwhichisn'tcaughtbytheprecedingconditions.a=......
  • [CISCN2019 华北赛区 Day1 Web2]ikun-1|python反序列化
    考点:JWT身份伪造、pythonpickle反序列化、逻辑漏洞1、打开之后首页界面直接看到了提示信息,信息如下:2、那就随便注册一个账号进行登录,然后购买lv6,但是未发现lv6,那就查看......
  • python之面向对象
    面向对象本质:将特定的数据与特定的功能绑定到一起将来只能彼此相互使用对象其实就是一个容器里面将数据和功能绑定到一起使用场景一:​ eg:游戏人物......​ ......