iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Python wmi 模块的学习
  • 527
分享到

Python wmi 模块的学习

模块Pythonwmi 2023-01-31 05:01:13 527人浏览 泡泡鱼

Python 官方文档:入门教程 => 点击学习

摘要

# -*- coding:utf-8 -*- import datetime import os import wmi import time import _winreg import pythoncom import threadin

# -*- coding:utf-8 -*-

import datetime
import os
import wmi
import time
import _winreg
import pythoncom
import threading
import win32api
import win32con
import Queue
c = wmi.WMI()

# 如果要连接远程机器,只需要在WMI构造器中指定远程机器名即可
# c = wmi.WMI("some_other_Machine")

# List All Running Processes 
# 列出所有正在运行的进程
for process in c.Win32_Process():
	print process.ProcessID,process.Name

# List All Running Notepad Processes
# 列出所有正在运行的记事本进程 
for process in c.Win32_Process(name="notepad.exe"):
	print process.ProcessID,process.Name

# Create And Then Destroy A New Notepad Process
# 创建一个新的记事本进程然后结束它
process_id, return_value = c.Win32_Process.Create(CommandLine="notepad.exe")
for process in c.Win32_Process(ProcessId=process_id):
	print process.ProcessID, process.Name

result = process.Terminate()

# Show The Interface For The .Create Method Of A Win32_Process Class
# 显示Win32_Process类的.Create方法的接口 
# 注:wmi模块会接受WMI方法的传入参数作为Python的关键字参数,并把传出参数作为一个元组进行返回。
print c.Win32_Process.Create

# Show All Automatic Servieces Which Are Not Running
# 显示没有处于正常运行状态的自启动服务
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 service stopped"

# Show The Percentage Free Space For Each Fixed Disk
# 显示每个固定磁盘的剩余空间百分比
for disk in c.Win32_LogicalDisk(DriveType=3):
	print disk.Caption, "%0.2f%% free" % (100.0 * long(disk.FreeSpace) / long(disk.Size) )

# Run Notepad, Wait Until It's Closed And Then Show Its Text
# 运行记事本,等它关闭之后显示它里面的文字 
# 注:这个例子是运行一个进程并且知道它什么时候结束,而不是去处理输入到记事本里面的文字。\
# 所以我们只是简单的用记事本打开一个指定文件,等到用户完成输入并关闭记事本之后,显示一下它的内容。 
filename = r'E:\Tools\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()

# Watch For New Print Jobs
# 监视新的打印任务
print_job_watcher = c.Win32_PrintJob.watch_for(
	notification_type = "Creation",
	delay_secs = 1
	)

while 1:
	pj = print_job_watcher()
	print "User %s has submitted %d pages to printer %s" % \
	(pj.Owner, pj.TotalPage, pj.Name)

# Reboot A Remote Machine
# 重启远程机器
# 注:要对远程系统进行这样的操作,WMI脚本必须具有远程关机(RemoteShutdown)的权限,\
# 也就是说你必须在连接别名中进行指定。WMI构造器允许你传入一个完整的别名,或者是指定你需要的那一部分。\
# 使用wmi.WMI.__init__的帮助文档可以找到更多相关内容。
# other_machine = "machine name of your choice"
d = wmi.WMI(computer=other_machine, privileges=["RemoteShutdown"])

os = d.Win32_OperatingSystem(Primary=1)[0]
os.Reboot()


# Show the IP and MAC addresses for IP-enabled network interfaces
# 对于启用IP的网卡显示其IP和MAC地址
for interface in c.Win32_NetWorkAdapterConfiguration(IPEnabled=1):
	print interface.Description, interface.MACAddress
	for ip_address in interface.IPAddress:
		print ip_address
	print 


# What’s running on startup and from where?
# 查看自启动项
for s in c.Win32_StartupCommand():
	print "[%s] %s <%s> " % (s.Location, s.Caption, s.Command) 


# Watch for errors in the event log
# 监视事件日志中的错误信息
e = wmi.WMI(privileges=["Security"])

watcher = e.watch_for(
	notification_type = "Creation",
	wmi_class = "Win32_NTLogEvent",
	Type = "error"
	)

while 1:
	error = watcher()
	print "Error in %s log: %s " % (error.Logfile, error.Message)
	# send mail to sysadmin etc.

# List reGIStry keys
# 列出注册表子键
# 注:本例及以下几例使用了Registry()这个方便的函数,此函数是早期加入到wmi包的,它等效于:
r = wmi.WMI(namespace="DEFAULT").StdRegProv
print r

r = wmi.Registry()
result, names = r.EnumKey(
	hDefKey = _winreg.HKEY_LOCAL_MACHINE,
	sSubKeyName = "Software"
	)

for key in names:
	print key

# Add a new registry key
# # 增加一个新的注册表子键
r = wmi.Registry()
result, = r.CreateKey(
	hDefKey = _winreg.HKEY_LOCAL_MACHINE,
	sSubKeyName = r"Software\TJG"
	)


# Add a new registry value
# 增加一个新的注册表键值
r = wmi.Registry()
result, = r.SetStringValue(
	hDefKey = _winreg.HKEY_LOCAL_MACHINE,
	sSubKeyName = r"Software\TJG",
	sValueName = "ApplicationName",
	sValue = "TJG APP"
	)

# Create a new IIS site
# # 创建一个新的IIS站点
k = wmi.WMI(namespace="MicrosoftIISv2")

#
# Could as well be achieved by doing:
#  WEB_server = c.IISWebService(Name="W3SVC")[0]
#

for web_server in k.IIsWebService(Name="W3SVC"):
	break

binding = k.new("ServerBinding")
binding.IP = ""
binding.Port = "8383"
binding.Hostname = ""
result, = web_server.CreateNewSite(
	PathOfRootVirtualDir = r"C:\inetpub\wwwroot",
	ServerComment = "My Web Site",
	ServerBinding = [binding.ole_object]
	)

# Show shared drives
# 显示共享目录

for share in c.Win32_Share():
	print share.Name, share.Path


# Show print jobs 
# 显示打印任务

for printer in c.Win32_Printer():
	print printer.Caption
	for job in c.Win32_PrintJob(DriverName=printer.DriverName):
		print " ", job.Document
	print 

# Show disk partitions
# 显示磁盘分区
for physical_disk in c.Win32_DiskDrive():
	for partition in physical_disk.associators("Win32_DiskDriveToDiskPartition"):
		for logic_disk in partition.associators("Win32_LogicalDiskToPartition"):
			print physical_disk.Caption, partition.Caption, logic_disk.Caption

# Install a product
# 安装一个产品

c.Win32_Product.Install(
	PackageLocation = 'E:\study\Python\python-2.7.8.msi',
	AllUsers = False
	)

# Connect to another machine as a named user
# 使用指定用户名连接另一台机器
# 注:你不能使用这个方法连接本机

#
# Using wmi module before 1.0rc3
#
connection = wmi.connect_server(
  server="other_machine",
  user="tim",
  passWord="secret"
)
n = wmi.WMI(wmi=connection)
 
#
# Using wmi module at least 1.0rc3
#
n = wmi.WMI(
  computer="other_machine",
  user="tim",
  password="secret"
)

# Show a method’s signature
# 显示一个方法的签名

for opsys in c.Win32_OperatingSystem():
	break

print opsys.Reboot
print opsys.Shutdown


# Schedule a job
# 创建任务计划
# 注:WMI的ScheduledJob类相当于windows的AT服务(通过at命令来控制)。

one_minute_time = datetime.datetime.now() + datetime.timedelta(minutes=1)
job_id, result = c.Win32_ScheduledJob.Create(
	Command=r"cmd.exe /c dir /b c:\ > c:\\temp.txt",
	StartTime=wmi.from_time(one_minute_time)
	)

print job_id

for line in os.popen("at"):
	print line


# Run a process minimised
# 最小化的方式运行一个进程

SW_SHOWNMINIMIZED = 1
startup = c.Win32_ProcessStartup.new(ShowWindow=SW_SHOWNMINIMIZED)
pid, result = c.Win32_Process.Create(
	CommandLine="notepad.exe",
	ProcessStartupInfORMation=startup
	)
print pid


# Find Drive Types
# 查看磁盘类型

DRIVE_TYPE = {
	0 : "Unkown",
	1 : "No Root Directory",
	2 : "Removable Disk",
	3 : "Local Disk",
	4 : "Network Drive",
	5 : "Compact Disc",
	6 : "RAM Disk"
}

for drive in c.Win32_LogicalDisk():
	print drive.Caption, DRIVE_TYPE[drive.DriveType]


# List Namespaces
# 列出命名空间

def enumerate_namespaces(namespace = u"root", level=0):
	print level * " ", namespace.split("/")[-1]
	c = wmi.WMI(namespace = namespace)
	for subnamespace in c.__NAMESPACE():
		enumerate_namespaces(namespace + "/" + subnamespace.Name, level + 1)

enumerate_namespaces()

# Use WMI in a thread
# 在线程中使用WMI 
# 注:WMI技术是基于COM的,要想在线程中使用它,你必须初始化COM的线程模式,就算你要访问一个隐式线程化的服务也是如此。
 
class Info(threading.Thread):
    def __init__(self):
    	threading.Thread.__init__(self)
    def run(self):
    	print 'In Another Thread...'
    	pythoncom.CoInitialize()
    	try:
      		c = wmi.WMI()
      		for i in range(5):
        		for process in c.Win32_Process():
          			print process.ProcessId, process.Name
        		time.sleep(2)
    	finally:
      		pythoncom.CoUninitialize()
 
if __name__ == '__main__':
  	print 'In Main Thread'
  	c = wmi.WMI()
  	for process in c.Win32_Process():
  		print process.ProcessId, process.Name
  	Info().start()


# Monitor multiple machines for power events
# 监控多台机器的电源事件 
class Server(threading.Thread):

	def __init__(self, results, server, user, password):

		threading.Thread.__init__(self)
		self.results = results
		self.server = server
		self.user = user
		self.password = password
		self.setDaemon(True)

	def run(self):
		pythoncom.CoInitialize()
		try:
			#
		    # If you don't want to use explicit loGons, remove
		    # the user= and password= params here and ensure
		    # that the user running *this* script has sufficient
		    # privs on the remote machines.
		    #
		    c = wmi.WMI(self.server, user = self.user, password = self.password)
		    power_watcher = c.Win32_PowerManagementEvent.watch_for()
		    while 1:
		    	self.results.put((self.server, power_watcher()))
		finally:
			pythoncom.CoUninitialize()

#
# Obviously, change these to match the machines
# in your network which probably won't be named
# after Harry Potter characters. And which hopefully
# use a less obvious admin password.
#

servers = [
	("goyle", "administator", "secret"),
	("malfoy", "administator", "secret")
	]

if __name__ == "__main__":
	power_events = Queue.Queue()
	for server, user, password in servers:
		print "Watching for", server
		Server(power_events, server, user, password).start()

	while 1:
		server, power_events = power_events.get()
		print server, "==>", power_events.EventType


# Find the current wallpaper
# 查看当前的墙纸

full_username = win32api.GetUserNameEx(win32con.NameSamCompatible)
for desktop in c.Win32_Desktop(Name = full_username):
	print desktop
	print \
		desktop.Wallpaper or "[No wallpaper]", \
		desktop.WallpaperStretched, desktop.WallpaperTiled


--结束END--

本文标题: Python wmi 模块的学习

本文链接: https://www.lsjlt.com/news/188071.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • Python wmi 模块的学习
    # -*- coding:utf-8 -*- import datetime import os import wmi import time import _winreg import pythoncom import threadin...
    99+
    2023-01-31
    模块 Python wmi
  • Python 模块学习
        模块学习: http://wsyht90.blog.51cto.com/9014030/1845737 1、getpass 2、os 3、sys 4、subprocess 5、hashlib 6、json 7、pickle 8、sh...
    99+
    2023-01-31
    模块 Python
  • python模块学习
    系统相关的信息模块: import sys sys.argv 是一个 list,包含所有的命令行参数. sys.stdout sys.stdin sys.stderr 分别表示标准输入输出,错误输出的文件对象. sys.st...
    99+
    2023-01-31
    模块 python
  • python模块学习----nmap模块
    安装nmap模块:pip install python_nmanmap模块说明:python-nmap是一个帮助使用nmap端口扫描器的python库。它允许轻松操纵nmap扫描结果,并且将是一个完美的选择,为需要自动完成扫描任务的系统管理...
    99+
    2023-01-31
    模块 python nmap
  • python模块学习(queue模块的Q
    学习版本3.5.2 PriorityQueue类和LifoQueue类继承Queue类然后重写了_init、_qsize、_put、_get这四个类的私有方法 Queue:先进先出队列的同步实现,通过双向列表实现的 # Initi...
    99+
    2023-01-31
    模块 python queue
  • Python模块学习之IPy模块
    IP地址规划是网络设计中非常重要的一个环节,规划的好坏会直接影响路由协议算法的效率,包括网络性能、可扩展性等方面,在这个过程当中,免不了要计算大量的IP地址,包括网段、网络掩码、广播地址、子网数、IP类型等。Python提供了一个强大的第...
    99+
    2023-01-31
    模块 Python IPy
  • Python pycurl模块 学习
    pycurl模块的安装方法如下: easy_install pycurl #easy_install安装方法 pip install pycurl #pip安装方法 #源码安装方法 # 要求curl-config包支持,需要源码方式重新安...
    99+
    2023-01-31
    模块 Python pycurl
  • Python学习-pycurl模块
    pycurl是一个用c语言编写的libcurl Python实现,功能非常强大,支持操作协议有FTP,HTTP,HTTPS,TELNET等。模块的常用方法说明:close()方法,对应libcurl包中的curl_easy_cleanup方...
    99+
    2023-01-31
    模块 Python pycurl
  • python模块学习(1)
    模块让你能够有逻辑地组织你的Python代码段。把相关的代码分配到一个 模块里能让你的代码更好用,更易懂。模块也是Python对象,具有随机的名字属性用来绑定或引用。简单地说,模块就是一个保存了Python代码的文件。模块能定义函数,类和变...
    99+
    2023-01-31
    模块 python
  • Python学习—json模块
    json模块 四个常用方法 son.dumps() 将python对象编码成为json的字符串格式(最常用的是字典,列表集合等都可以) json.dump() 将python对象编码成为json的字符串格式并写入文件 json...
    99+
    2023-01-31
    模块 Python json
  • python学习-re模块
    Python 的 re 模块(Regular Expression 正则表达式)提供各种正则表达式的匹配操作,在文本解析、复杂字符串分析和信息提取时是一个非常有用的工具,下面我主要总结了re的常用方法。1.re的简介    使用python...
    99+
    2023-01-31
    模块 python
  • python optparse模块学习
    本文参考:http://docs.python.org/2/library/optparse.htmlPython 有两个内建的模块用于处理命令行参数:一个是 getopt,getopt只能简单处理 命令行参数。另一个是 optparse,...
    99+
    2023-01-31
    模块 python optparse
  • python学习-psuti模块
    psutil(进程和系统实用程序)是一个跨平台的库,用于 在Python中检索有关运行进程和系统利用率(CPU,内存,磁盘,网络,传感器)的信息。它主要用于系统监视,分析和限制流程资源以及运行流程的管理。它实现了UNIX命令行工具提供的许多...
    99+
    2023-01-31
    模块 python psuti
  • Python模块学习--email
    可以使用Python的email模块来实现带有附件的邮件的发送。 SMTP (Simple Mail Transfer Protocol)   邮件传送代理 (Mail Transfer Agent,MTA) 程序...
    99+
    2023-01-31
    模块 Python email
  • python学习-smtplib模块
     python的stmplib模块可以实现邮件的发送功能,可以模拟一个smtp客户端。在python2.3或者更高版本默认自带smtplib模块,无需额外安装。一、smtplibi模块的常用类与方法    smtp类定义:smtplib([...
    99+
    2023-01-31
    模块 python smtplib
  • python hashlib模块学习
    目录 hashlib 模块 破解密码 hmac 模块 1.干嘛用的: 对字符进行加密,其实就是一个自定义的字符编码表,...
    99+
    2023-01-31
    模块 python hashlib
  • python学习-OS模块
    OS模块是python内建模块,主要是对大量文件和大量路径进行操作os.sep:取代操作系统特定的路径分隔符 os.name:指示你正在使用的工作平台。比如对于Windows,它是'nt',而对于Linux/Unix用户,它是'posix'...
    99+
    2023-01-31
    模块 python OS
  • Python 常用模块学习
    Python中的模块是可以将代码量较大的程序分割成多个有组织的、彼此独立但又能互相交互的代码片段,这些自我包含的有组织的代码段就是模块。Python允许“导入”其他模块以实现代码重用,从而也实现了将独立的代码文件组织成更大的程序系统。Py...
    99+
    2023-01-31
    模块 常用 Python
  • python中pickle模块学习
       在python中有一个pickle的标准模块,这个模块可以把几乎python中所有类型通过模块转换成pickle所能识别的格式进行存储。  pickel模块主要有两个函数dump()和load()  dump()可以把数据对象以特定...
    99+
    2023-01-31
    模块 python pickle
  • Python学习—paramiko模块实
    paramiko模块 paramiko模块提供了ssh及sft进行远程登录服务器执行命令和上传下载文件的功能。这是一个第三方的软件包,使用之前需要安装。 import paramiko # ssh root@ip # 创建一个ssh对象 ...
    99+
    2023-01-31
    模块 Python paramiko
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作