2011年6月3日星期五

Windows Management Instrument

WMI是其中一個Windows Management interface,可經由不同途徑使用;如PowerShell,但要學過另一種command syntax;wmic command,不用安裝,隨OS附送,好用但不太方便;寫VBScript,講笑啦,寧願吊頸都唔寫VBScript,係寫都用Python寫。

只要安裝兩個package,pywin32WMI便可。

""" Query Windows Host Information
"""

import argparse
import wmi
import configparser


class WindowsHost():
    """ Host connect through WMI
    """

    def __init__(self, host, username, password):
        '''Connect to Windows Host through WMI'''
        self._wmi = wmi.WMI(host, user=username, password=password)

    def process_run(self, command):
        process_id, result = self._wmi.Win32_process.Create(command)
        watcher = c.watch_for(notification_type="Deletion", wmi_class="Win32_Process", delay_secs=1,
                              ProcessId=process_id)
        watcher()

    def system_result(self):
        '''Query system name, domain/workgroup, model and installed memory '''
        for m in self._wmi.Win32_ComputerSystem():
            yield '{:16} {:18} {:30} {:5}MB'.format(m.Name, m.Domain, m.Model,
                                                    int(m.TotalPhysicalMemory) // 1024**2)

    def network_result(self):
        '''Query host network interface, hostname, MAC address, DHCP, IP address,
        subnet mask and default gateway
        '''
        for m in self._wmi.Win32_NetworkAdapterConfiguration(IPEnabled=1):
            yield '{} {} {} {} {} {}\n'.format(m.DNSHostName, m.MACAddress, m.DHCPEnabled,
                                               ' '.join(m.IPAddress),
                                               ' '.join(m.IPSubnet),
                                               ' '.join(m.DefaultIPGateway or []))

    def process_result(self):
        '''Query host running processes '''
        for m in self._wmi.Win32_process():
            yield '{:5} {:5} {}'.format(m.ProcessId, m.ParentProcessId, m.ExecutablePath or m.Name)

    def model_result(self):
        '''Query host machine serial number '''
        for m in self._wmi.Win32_SystemEnclosure():
            yield '{}'.format(m.SerialNumber)

    def hardware_result(self):
        '''Query host machine serial number '''
        for m in self._wmi.Win32_PnPEntity():
            yield '{} = {}'.format(m.Name, m.Status)

    def software_result(self):
        '''Query host machine software '''
        for m in self._wmi.Win32_Product():
            yield '{} {}'.format(m.Name, m.Version)

if __name__ == '__main__':
    config = configparser.ConfigParser()
    config.read('setting.ini')
    config['localhost'] = {'host': '.', 'user': '', 'password': ''}

    parser = argparse.ArgumentParser(description='Windows Host Query')
    parser.set_defaults(query="model")
    parser.add_argument("-i", "--ip", action="store_const", dest="query", const="network", help="network setting")
    parser.add_argument("-p", "--process", action="store_const", dest="query", const="process", help="running process")
    parser.add_argument("-s", "--serial", action="store_const", dest="query", const="model", help="serial no.")
    parser.add_argument("-x", "--hardware", action="store_const", dest="query", const="hardware", help="hardware configuration")
    parser.add_argument("--software", action="store_const", dest="query", const="software", help="software installation")
    parser.add_argument("--system", action="store_const", dest="query", const="system", help="system configuration")
    parser.add_argument("--version", action='version', version='%(prog)s 1.2')
    parser.add_argument("target", nargs='*', default=['localhost'], help="run command in target machine")
    args = parser.parse_args()

    for t in args.target:
        c = config[t]
        h = WindowsHost(c['host'], c['user'], c['password'])
        for i in getattr(h, args.query + "_result")():
            print(i)

這script先讀setting.ini,內裡載有要查詢的Windows Host network address,user name和password。


[target]
host = 1.1.1.1
user = administrator
password = password

然後根據不同的parameter查詢host的network setting,running process,machine serial no.,hardware configuration或己安裝的software。

功能暫時係咁多,遲吓加埋remote install/uninstall就差不多啦。

沒有留言:

發佈留言