Python 基础之wmi模块(windows监控)
背景:
最近学习 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