Python监视进程创建情况和系统服务状态

2016-07-01 董付国 Python小屋 Python小屋

(1)监视Windows系统中进程创建情况 

import wmi

c = wmi.WMI()

process_watcher = c.Win32_Process.watch_for('creation')

while True:

    try:

        new_process = process_watcher()

        proc_owner = '{0[0]}\\{0[1]}'.format(new_process.GetOwner())

        temp_creation_date = new_process.CreationDate

        creation_date = temp_creation_date[:4]

        for i in (4, 6):

            creation_date += '-'+temp_creation_date[i:i+2]

        creation_date += ' '

        for i in (8, 10, 12):

            creation_date += temp_creation_date[i:i+2]+':'

        creation_date = creation_date[:-1]

        executable = new_process.ExecutablePath

        cmdline = new_process.CommandLine

        pid = new_process.ProcessId

        parent_pid = new_process.ParentProcessId

        print('='*30)

        print('Process owner:'.ljust(18), proc_owner)

        print('Creation Time:'.ljust(18), str(creation_date))

        print('Executable:'.ljust(18), executable)

        print('Cmdline:'.ljust(18), cmdline)

        print('ProcessId:'.ljust(18), pid)

        print('Parent ProcessId:'.ljust(18), parent_pid)

    except:

        pass
(2)查看Windows系统中服务状态
import itertools

import wmi

def group(service):

    if service.State == 'Stopped':

        return 'Stopped'

    elif service.State == 'Running':

        return 'Running'

    else:

        return 'Others'

result = dict()

c = wmi.WMI()

for service in c.Win32_Service():

    state = service.State

    caption = service.Caption

    t = result.get(state,[])

    t.append(caption)

    result[state] = t

for state, captions in result.items():

    print('='*30)

    print(state)

    print('\n'.join(sorted(captions)))