您当前的位置:首页 > 计算机 > 编程开发 > Python

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

时间:09-03来源:作者:点击数:

(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)))

方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门