首页 > 系统相关 >Python 基础之wmi模块(windows监控)

Python 基础之wmi模块(windows监控)

时间:2022-11-19 18:46:47浏览次数:65  
标签:process 20 center Python Win32 windows wmi print disk

背景:

  最近学习 Python 监控系统状态的Psutil模块时。看到很多函数都是针对某些系统(如Linux、FreeBSD )的时就在想,既然有那么多监听系统状态的函数没有兼容win系统

那么是不是应该还有某些模块,可以单独为win系统 服务于监听其系统状态呢?这一搜还真的让我找到了 WMI 一个由微软官方维护发行的模块,开发放了很多调用windows

底层,和获取win系统配置,状态等信息的接口,OK,老样子废话少说,直接给小伙伴们梦整理好最全,最简单“开箱即用”的代码。

(因为 博客园 写起来不是很舒服,所以 想了解更多 Python 学习/使用 的可以直接 戳这里=》https://www.yuque.com/mangofish Python从入门到入土 )

安装OR引入:

#安装
pip install wmi
# OR
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple wmi-U

#导入
import wmi
# 如果觉得名字太长也可以重命名使用哦
import wmi as w

开箱使用

CPU

    #cpu*类型**
    print('cpu*类型*'.center(20,'~'))
    for cpu in c.Win32_Processor():
        print ("CPUID:", cpu.ProcessorId.strip())
        print ("Processor ID: %s" % cpu.DeviceID)
        print ("Process Name: %s" % cpu.Name.strip())

硬盘

    #硬盘***
    print('硬盘'.center(20,'~'))
    for disk in c.Win32_DiskDrive():
        print ('disk id:', disk.SerialNumber.strip())
#获取硬盘信息与分区情况*** print('获取硬盘信息和分区情况'.center(20,'~')) for physical_disk in c.Win32_DiskDrive (): for partition in physical_disk.associators ("Win32_DiskDriveToDiskPartition"): for logical_disk in partition.associators ("Win32_LogicalDiskToPartition"): print (physical_disk.Caption, partition.Caption, logical_disk.Caption)
#显示硬盘可用百分比*** print('显示硬盘可用百分比'.center(20,'~')) for disk in c.Win32_LogicalDisk (DriveType=3): print (disk.Caption, "%0.2f%% free" % (100.0 * int(disk.FreeSpace) / int(disk.Size)))

主板

    #主板***
    print('主板'.center(20,'~'))
    for board in c.Win32_BaseBoard():
        print ("main board id:", board.SerialNumber.strip())

设备地址

    #mac地址
    print('mac地址'.center(20,'~'))
    for networkAdapter in c.Win32_NetworkAdapterConfiguration (IPEnabled = True):
        print ("mac address:", networkAdapter.MACAddress)
#打印IP和MAC地址*** print('显示IP和MAC'.center(20,'~')) for interface in c.Win32_NetworkAdapterConfiguration (IPEnabled=1): print (interface.Description, interface.MACAddress) for ip_address in interface.IPAddress: print (ip_address)

BIOS

    #bios***
    print('bios'.center(20,'~'))
    for bios in c.Win32_BIOS():
        print ("bios number:", bios.SerialNumber.strip())

内存

    #内存大小***
    print('内存大小'.center(20,'~'))
    totalMemSize=0
    for memModule in c.Win32_PhysicalMemory():
      totalMemSize+=int(memModule.Capacity)
    print ("Memory Capacity: %.2fMB" %(totalMemSize/1048576))

进程

    #所有进程***
    print('所有进程'.center(20,'~'))
    for process in c.Win32_Process ():
        print ("%5s %s" % (process.ProcessId, process.Name))
#指定进程*** print('输出指定服务Pid号'.center(20,'~')) for process in c.Win32_Process (name="YoudaoDict.exe"): print ("进程号(PID): %5s; 服务名: %s" % (process.ProcessId, process.Name))
#打开服务,监听其进程,2s后终止该进程*** print('打开服务,监听其进程,2s后终止该进程'.center(20,'~')) process_id, return_value = c.Win32_Process.Create (CommandLine="notepad.exe") for process in c.Win32_Process (ProcessId=process_id): print ("进程号(PID): %5s; 服务名: %s" % (process.ProcessId, process.Name)) time.sleep(2) process.Terminate() #关闭这个进程服务

文件夹/路径

    #显示共享文件夹及其路径***
    print('显示共享文件夹及其路径'.center(20,'~'))
    for share in c.Win32_Share ():
        print ("共享文件: %6s; 路径: %s" % (share.Name, share.Path))

服务

    #显示 自动服务和当前未启动的服务***
    print('显示服务和当前未启动的服务'.center(20,'~'))
    stopped_services = c.Win32_Service (StartMode="Auto", State="Stopped")
    if stopped_services:
        for s in stopped_services:
            print (s.Caption+"   "+ "service is not running")
    else:
        print ("No auto services stopped")
#脚本运行程序,并等待直到它关闭,并且显示内容*** print('运行记事本,等待直到它关闭,并且文件内容'.center(20,'~')) filename = r"C:\\Users\Administrator\Desktop\\test.txt" process = c.Win32_Process process_id, result = process.Create (CommandLine="notepad.exe " + filename) watcher = c.watch_for ( notification_type="Deletion", wmi_class="Win32_Process", delay_secs=1, ProcessId=process_id ) watcher () print ("This is what you wrote:") print (open(filename).read())
#自启动 程序,位置和命令*** print('自启动程序,位置和命令'.center(20,'~')) for s in c.Win32_StartupCommand (): print ("[%s] %s <%s>" % (s.Location, s.Caption, s.Command))

简单封装

进程信息太多了,一下封装省略。如果需要查看众多进程信息,请自行封装或打印哦

编译为 .exe  程序

# -*- coding: utf-8 -*-
import wmi
import os

# 声明
Statement = """
使用说明:\n
1 请打开计算机基础配置文件夹,进入到dist目录下,双击运行:基础配置信息.exe 文件(此文件)\n
2 在命令行窗口输入保存的文件名,运行完成后打开生成的txt文本即可查看获取到的计算机基础配置信息
"""
print(Statement)
while True:
    fname=input('enter filename>')
    if os.path.exists(fname):
        print("Error:'%s' already exists" %fname)
    else:
        break
# open函数在打开目录中进行检查,如果有则打开,否则新建
fobj=open(fname,'a',encoding='utf-8')

# 获取操作系统版本信息
def sys_version():
    c = wmi.WMI()
    for sys in c.Win32_OperatingSystem():
        print("操作系统版本:%s" % sys.Caption)
        fobj.write('操作系统版本:' + sys.Caption)
        print("操作系统位数:",sys.OSArchitecture)
        fobj.write('\n' + '操作系统位数:' + sys.OSArchitecture)
# 获取机器IP和MAC地址以及网卡类型
def getIP():
    c = wmi.WMI()
    for interface in c.Win32_NetworkAdapterConfiguration(IPEnabled=1):
        print("网口型号为:",interface.Description)
        fobj.write('\n' + '网口型号为:' + interface.Description)
        for ip_address in interface.IPAddress:
            print(ip_address)
            fobj.write('\n' + 'IP地址和MAC地址:' + ip_address)
# 获取CPU和内存大小
def cpu_and_mem():
    c = wmi.WMI()
    for cpu in c.Win32_Processor():
        print("CPU: %s" % cpu.Name.strip())
        fobj.write('\n' + 'CPU:' + cpu.Name.strip())
    for Memory in c.Win32_PhysicalMemory():
        print("内存大小: %.fGB" % ( (int(Memory.Capacity) / 1048576) /1024) )
        fobj.write('\n' + "内存大小: %.fGB" % ( (int(Memory.Capacity) / 1048576) /1024) )
# 获取磁盘分区和各分区大小
def disk():
    c = wmi.WMI()
    # 获取硬盘分区
    for physical_disk in c.Win32_DiskDrive():
        for partition in physical_disk.associators("Win32_DiskDriveToDiskPartition"):
            for logical_disk in partition.associators("Win32_LogicalDiskToPartition"):
                print(physical_disk.Caption, partition.Caption, logical_disk.Caption)
                fobj.write('\n' + '磁盘分区:' + physical_disk.Caption + partition.Caption + logical_disk.Caption)
    # 获取各个磁盘分区大小
    for disk in c.Win32_LogicalDisk(DriveType=3):
        # print(disk.Caption, "%0.2f%% free" % (100.0 * int(disk.FreeSpace) / int(disk.Size)))
        print(disk.Caption,"磁盘大小: %0.1fGB, 剩余空间:%0.2f%%" % ((int(disk.Size) / 1048576) / 1024,100.0 * int(disk.FreeSpace) / int(disk.Size)))
        fobj.write('\n' +disk.Caption + "磁盘大小: %0.1fGB, 剩余空间:%0.2f%%" % ((int(disk.Size) / 1048576) / 1024,100.0 * int(disk.FreeSpace) / int(disk.Size)))
def main():
    sys_version()
    getIP()
    cpu_and_mem()
    disk()
if __name__ == '__main__':
    main()

fobj.close()

不编译,正常打印查看

import wmi
import time

def PrintDiskInfo():
    c = wmi.WMI()
    #cpu*类型**
    print('cpu*类型*'.center(20,'~'))
    for cpu in c.Win32_Processor():
        print ("CPUID:", cpu.ProcessorId.strip())
        print ("Processor ID: %s" % cpu.DeviceID)
        print ("Process Name: %s" % cpu.Name.strip())
    #硬盘***
    print('硬盘'.center(20,'~'))
    for disk in c.Win32_DiskDrive():
        print ('disk id:', disk.SerialNumber.strip())
    #获取硬盘信息与分区情况***
    print('获取硬盘信息和分区情况'.center(20,'~'))
    for physical_disk in c.Win32_DiskDrive ():
        for partition in physical_disk.associators ("Win32_DiskDriveToDiskPartition"):
            for logical_disk in partition.associators ("Win32_LogicalDiskToPartition"):
                print (physical_disk.Caption, partition.Caption, logical_disk.Caption)
    #显示磁盘可用百分比***
    print('显示磁盘可用百分比'.center(20,'~'))
    for disk in c.Win32_LogicalDisk (DriveType=3):
        print (disk.Caption, "%0.2f%% free" % (100.0 * int(disk.FreeSpace) / int(disk.Size)))
    #主板***
    print('主板'.center(20,'~'))
    for board in c.Win32_BaseBoard():
        print ("main board id:", board.SerialNumber.strip())
    #mac地址
    print('mac地址'.center(20,'~'))
    for networkAdapter in c.Win32_NetworkAdapterConfiguration (IPEnabled = True):
        print ("mac address:", networkAdapter.MACAddress)
    #显示IP和MAC***
    print('显示IP和MAC'.center(20,'~'))
    for interface in c.Win32_NetworkAdapterConfiguration (IPEnabled=1):
        print (interface.Description, interface.MACAddress)
    for ip_address in interface.IPAddress:
      print (ip_address)
    #bios***
    print('bios'.center(20,'~'))
    for bios in c.Win32_BIOS():
        print ("bios number:", bios.SerialNumber.strip())
    #内存大小***
    print('内存大小'.center(20,'~'))
    totalMemSize=0
    for memModule in c.Win32_PhysicalMemory():
      totalMemSize+=int(memModule.Capacity)
    print ("Memory Capacity: %.2fMB" %(totalMemSize/1048576))
    # #所有进程***
    # print('所有进程'.center(20,'~'))
    # for process in c.Win32_Process ():
    #     print ("%5s %s" % (process.ProcessId, process.Name))
    # #指定进程***
    # print('输出指定服务Pid号'.center(20,'~'))
    # for process in c.Win32_Process (name="YoudaoDict.exe"): 
    #     print ("进程号(PID): %5s; 服务名: %s" % (process.ProcessId, process.Name))
    # #打开服务,监听其进程,2s后终止该进程***
    # print('打开服务,监听其进程,2s后终止该进程'.center(20,'~'))
    # process_id, return_value = c.Win32_Process.Create (CommandLine="notepad.exe")
    # for process in c.Win32_Process (ProcessId=process_id):
    #     print ("进程号(PID): %5s; 服务名: %s" % (process.ProcessId, process.Name))
    #     time.sleep(2)
    #     process.Terminate() #关闭这个进程服务
    #显示共享文件夹及其路径***
    print('显示共享文件夹及其路径'.center(20,'~'))
    for share in c.Win32_Share ():
        print ("共享文件: %6s; 路径: %s" % (share.Name, share.Path))
    #显示为自动,当前未启动的服务***
    print('显示为自动,当前未启动的服务'.center(20,'~'))
    stopped_services = c.Win32_Service (StartMode="Auto", State="Stopped")
    if stopped_services:
        for s in stopped_services:
            print (s.Caption+"   "+ "service is not running")
    else:
        print ("No auto services stopped")
    #运行记事本,等待直到它关闭,并且显示内容***
    print('运行记事本,等待直到它关闭,并且文件内容'.center(20,'~'))
    filename = r"C:\\Users\Administrator\Desktop\\test.txt"
    process = c.Win32_Process
    process_id, result = process.Create (CommandLine="notepad.exe " + filename)
    watcher = c.watch_for (
        notification_type="Deletion",
        wmi_class="Win32_Process",
        delay_secs=1,
        ProcessId=process_id
    )
    watcher ()
    print ("This is what you wrote:")
    print (open(filename).read())
    #自启动程序,位置和命令***
    print('自启动程序,位置和命令'.center(20,'~'))
    for s in c.Win32_StartupCommand ():
        print ("[%s] %s <%s>" % (s.Location, s.Caption, s.Command))

if __name__ == "__main__":
    PrintDiskInfo()

推荐手册

都是干货

汉化 WMI汉化手册 

推荐 官方手册

个人  https://www.yuque.com/mangofish/mkgz40

   https://www.likecs.com/show-307016180.html

 

标签:process,20,center,Python,Win32,windows,wmi,print,disk
From: https://www.cnblogs.com/mangofish/p/16906626.html

相关文章

  • python网页爬虫开局通用示例
    万事开头难,好的开始是成功的一半。步骤:1、导入requests模块,2、get方法(url,timeout,headers等)3、状态判断,4、考虑编码,5、try方法判断异常。importrequests#importtimedef......
  • python-迭代器
     迭代的概念使用for循环遍历取值的过程叫做迭代,比如:使用for循环遍历列表获取值的过程#Python中的迭代forvaluein[2,3,4]:print(value)复制代码1.2......
  • 【mysql】关于python建立mysql相关操作
    1.安装用pip安装指令pipinstallpymysql查看安装成功#cmdpipshowmysql#cmd找list中有该软件piplist#python中不报错importpymysql2.操作流程3.封装......
  • 深度学习与通信交叉领域的python包:deepcom
    什么是deepcom在进行深度学习与通信领域的交叉研究时,有一些反复使用的算法与训练流程。但是现有的学习框架主要集中在网络的训练部分,对于通信领域的参数压缩与高效传输并......
  • Python学习笔记(三)
    运算符和表达式算术运算python在这里直接支持了幂运算,c的话需要额外的头文件导入此外,python也是支持取模%和取整运算的。The / (division)and // (floordivisi......
  • Linux与Windows功能的区别
    1.Linux模块化程度高Linux的内核分成进程调度、内存管理、进程间通信、虚拟文件系统和网络接口五大部分;其独特的模块机制可根据用户的需要,实时地将某些模块插入或从内......
  • Python的线程如何理解
    Num01-->多线程threadingPython中建议使用threading模块,而不要使用thread模块。原因如下:1,Python中threading模块对thread进行了一些包装,可以更加方便的使用。2,Python......
  • python3标准库
    本文出处 http://www.cnblogs.com/vamei   作者:Vamei序列(sequence)序列包含有定值表(tuple)和表(list)。字符串(string)是一种特殊的定值表下面的内建函数(buil......
  • python 协程学习笔记
    yield生成器frominspectimportgetgeneratorstatedefgen1():x=yield2print(x)y=yieldxreturnyg=gen1()print(getgeneratorstate(......
  • python第五章pta习题总结
    四、编程部分1、sorted函数:sorted(iterable,cmp=None,key=None,reverse=False)#iterable:可迭代的对象#cmp:比较规则#key:用来进行比较的对象,只有一个参数2、eval()......