Python wmi Cookbook 中文翻譯

簡介:

本文全部的例均是假設你在使用來自http://timgolden.me.uk/python/wmi/cookbook.html的WMI模塊。使用此模塊,你能夠在Windows系統中去體驗下面這些實用的例子。或許你將由此瞭解到WMI的冰山一角。

下面這些例子,除非有特別說明,均假設你要鏈接的是當前的機器。若是要鏈接遠程機器,只須要在WMI構造器中指定遠程機器名便可: html

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
相關文章
相關標籤/搜索