Python wmi Cookbook 中文翻译

2013/09/12 23:39
阅读数 3.5K
简介:

本文所有的例均是假设你在使用来自http://timgolden.me.uk/python/wmi/cookbook.html的WMI模块。使用此模块,你可以在Windows系统中去体验下面这些实用的例子。或许你将由此了解到WMI的冰山一角。

下面这些例子,除非有特别说明,均假设你要连接的是当前的机器。如果要连接远程机器,只需要在WMI构造器中指定远程机器名即可:

import wmi
c = wmi.WMI("some_other_machine")
注:这都是些完整的例子,你可以直接复制粘贴到一个.py文件里面,也可以复制粘贴到Python命令行交互窗口(原文作者是在Windows2000系统的CMD窗口做的测试)。

实例:

列出所有正在运行的进程


import wmi
c = wmi.WMI()

for process in c.Win32_Process():
  print process.ProcessId, process.Name
列出所有正在运行的记事本进程


import wmi
c = wmi.WMI()

for process in c.Win32_Process(name="notepad.exe"):
  print process.ProcessId, process.Name
创建一个新的记事本进程然后结束它


import wmi
c = wmi.WMI()

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()
显示Win32_Process类的.Create方法的接口

注:wmi模块会接受WMI方法的传入参数作为Python的关键字参数,并把传出参数作为一个元组进行返回。


import wmi
c = wmi.WMI()

print c.Win32_Process.Create
显示没有处于正常运行状态的自启动服务


import wmi
c = wmi.WMI()

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"
显示每个固定磁盘的剩余空间百分比


import wmi
c = wmi.WMI()

for disk in c.Win32_LogicalDisk(DriveType=3):
  print disk.Caption, "%0.2f%% free" %(100.0 * long(disk.FreeSpace) / long(disk.Size))
运行记事本,等它关闭之后显示它里面的文字

注:这个例子是运行一个进程并且知道它什么时候结束,而不是去处理输入到记事本里面的文字。所以我们只是简单的用记事本打开一个指定文件,等到用户完成输入并关闭记事本之后,显示一下它的内容。

本例不适用于远程机器,因为处于安全考虑,在远程机器上启动的进程是没有界面的(你在桌面上是看不到它们的)。这类远程操作的技术多用于在服务器上运行一个安装程序,安装结束之后重启机器。


import wmi
c = wmi.WMI()

filename = r"c:\temp\temp.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()
监视新的打印任务


import wmi
c = wmi.WMI()

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.TotalPages, pj.Name)
重启远程机器

注:要对远程系统进行这样的操作,WMI脚本必须具有远程关机(RemoteShutdown)的权限,也就是说你必须在连接别名中进行指定。WMI构造器允许你传入一个完整的别名,或者是指定你需要的那一部分。使用wmi.WMI.__init__的帮助文档可以找到更多相关内容。


import wmi
# other_machine = "machine name of your choice"
c = wmi.WMI(computer=other_machine, privileges=["RemoteShutdown"])

os = c.Win32_OperatingSystem(Primary=1)[0]
os.Reboot()
对于启用IP的网卡显示其IP和MAC地址


import wmi
c = wmi.WMI()

for interface in c.Win32_NetworkAdapterConfiguration(IPEnabled=1):
  print interface.Description, interface.MACAddress
  for ip_address in interface.IPAddress:
    print ip_address
  print
查看自启动项

import wmi
c = wmi.WMI()

for s in c.Win32_StartupCommand():
  print "[%s] %s <%s>" %(s.Location, s.Caption, s.Command)
监视事件日志中的错误信息

import wmi
c = wmi.WMI(privileges=["Security"])

watcher = c.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.
列出注册表子键

注:本例及以下几例使用了Registry()这个方便的函数,此函数是早期加入到wmi包的,它等效于:
import wmi
r = wmi.WMI(namespace="DEFAULT").StdRegProv
import _winreg
import wmi

r = wmi.Registry()
result, names = r.EnumKey(
  hDefKey=_winreg.HKEY_LOCAL_MACHINE,
  sSubKeyName="Software"
)
for key in names:
  print key
增加一个新的注册表子键

import _winreg
import wmi

r = wmi.Registry()
result, = r.CreateKey(
  hDefKey=_winreg.HKEY_LOCAL_MACHINE,
  sSubKeyName=r"Software\TJG"
)
增加一个新的注册表键值

import _winreg
import wmi

r = wmi.Registry()
result, = r.SetStringValue(
  hDefKey=_winreg.HKEY_LOCAL_MACHINE,
  sSubKeyName=r"Software\TJG",
  sValueName="ApplicationName",
  sValue="TJG App"
)
创建一个新的IIS站点

import wmi
c = wmi.WMI(namespace="MicrosoftIISv2")

#
# Could as well be achieved by doing:
#  web_server = c.IISWebService(Name="W3SVC")[0]
#
for web_server in c.IIsWebService(Name="W3SVC"):
  break

binding = c.new("ServerBinding")
binding.IP = ""
binding.Port = "8383"
binding.Hostname = ""
result, = web_server.CreateNewSite(
  PathOfRootVirtualDir=r"c:\inetpub\wwwroot",
  ServerComment="My Web Site",
  ServerBindings= [binding.ole_object]
)
显示共享目录

import wmi
c = wmi.WMI()

for share in c.Win32_Share():
  print share.Name, share.Path
显示打印任务

import wmi
c = wmi.WMI()

for printer in c.Win32_Printer():
  print printer.Caption
  for job in c.Win32_PrintJob(DriverName=printer.DriverName):
    print "  ", job.Document
  print
显示磁盘分区

import wmi
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
安装一个产品

import wmi
c = wmi.WMI()

c.Win32_Product.Install(
  PackageLocation="c:/temp/python-2.4.2.msi",
  AllUsers=False
)
使用指定用户名连接另一台机器

注:你不能使用这个方法连接本机

import wmi

#
# Using wmi module before 1.0rc3
#
connection = wmi.connect_server(
  server="other_machine",
  user="tim",
  password="secret"
)
c = wmi.WMI(wmi=connection)

#
# Using wmi module at least 1.0rc3
#
c = wmi.WMI(
  computer="other_machine",
  user="tim",
  password="secret"
)
显示一个方法的签名

import wmi
c = wmi.WMI ()
for opsys in c.Win32_OperatingSystem ():
  break

print opsys.Reboot
print opsys.Shutdown
创建任务计划

注:WMI的ScheduledJob类相当于Windows的AT服务(通过at命令来控制)。

import os
import wmi

c = wmi.WMI ()
one_minutes_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_minutes_time)
)
print job_id

for line in os.popen("at"):
  print line
以最小化的方式运行一个进程

import wmi

SW_SHOWMINIMIZED = 1

c = wmi.WMI()
startup = c.Win32_ProcessStartup.new(ShowWindow=SW_SHOWMINIMIZED)
pid, result = c.Win32_Process.Create(
  CommandLine="notepad.exe",
  ProcessStartupInformation=startup
)
print pid
查看磁盘类型

import wmi

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

c = wmi.WMI()
for drive in c.Win32_LogicalDisk():
  print drive.Caption, DRIVE_TYPES[drive.DriveType]
列出命名空间

import wmi

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()
在线程中使用WMI

注:WMI技术是基于COM的,要想在线程中使用它,你必须初始化COM的线程模式,就算你要访问一个隐式线程化的服务也是如此。

import pythoncom
import wmi
import threading
import time

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()
监控多台机器的电源事件

注:这个例子演示了外部事件、线程、远程监控等,所有这些都在一个小小的包里面!无论一台机器何时进入或退出挂起状态,电源子系统都会通过WMI产生一个外部事件。外部事件是非常有用的,因为WMI不必轮询也可以保证你不会错过任何事件。这里的多台机器只是使用进程的一个实际例子而已。

import pythoncom
import wmi
import threading
import Queue

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 True:
        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", "administrator", "secret"),
  ("malfoy", "administrator", "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 True:
    server, power_event = power_events.get()
    print server, "=>", power_event.EventType
查看当前的墙纸

import wmi
import win32api
import win32con

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

展开阅读全文
打赏
2
11 收藏
分享
加载中
更多评论
打赏
0 评论
11 收藏
2
分享
返回顶部
顶部