Python管理Windows进程

用python获得正在的运行的windows进程的有几种方式:

方式一

通过 PyWin32包对Windows进行处理。
可以通过这个获取系统信息,但仅限于windows系统。

import win32com.client
wmi=win32com.client.GetObject('winmgmts:')
for p in wmi.InstancesOf('win32_process'):
    print p.Name, p.Properties_('ProcessId'), \
        int(p.Properties_('UserModeTime').Value)+int(p.Properties_('KernelModeTime').Value)
    children=wmi.ExecQuery('Select * from win32_process where ParentProcessId=%s' %p.Properties_('ProcessId'))
    for child in children:
        print '\t',child.Name,child.Properties_('ProcessId'), \
            int(child.Properties_('UserModeTime').Value)+int(child.Properties_('KernelModeTime').Value)

运行结果:

System Idle Process 0 11055150937500
    System Idle Process 0 11055150937500
    System 4 14906718750
System 4 14906718750
    smss.exe 864 937500
smss.exe 864 937500
    csrss.exe 916 1752187500
    winlogon.exe 940 72812500
csrss.exe 916 1752187500
winlogon.exe 940 72812500
    services.exe 1024 324236406250
    lsass.exe 1044 10099062500
services.exe 1024 324236406250
    svchost.exe 1236 35468750
    svchost.exe 1304 6174687500
    svchost.exe 1480 198943593750
    svchost.exe 1524 35156250
    svchost.exe 1636 1412656250
    svchost.exe 1688 494843750
    spoolsv.exe 1860 45312500
    DhMachineSvc.exe 2040 23593750
    jqs.exe 200 11605000000
    NTFSWatcher.exe 248 15625000
    OmniAddrService.exe 268 86406250
    pcas.exe 396 172187500
    nssm.exe 696 2968750
    TeamViewer_Service.exe 772 172343750
    winvnc4.exe 844 78750000
    svchost.exe 880 151718750
    alg.exe 3208 56093750
lsass.exe 1044 10099062500
svchost.exe 1236 35468750
    wmiprvse.exe 5184 2500000
svchost.exe 1304 6174687500
svchost.exe 1480 198943125000
svchost.exe 1524 35156250
svchost.exe 1636 1412656250
svchost.exe 1688 494843750
spoolsv.exe 1860 45312500
DhMachineSvc.exe 2040 23593750
jqs.exe 200 11605000000
GoogleUpdate.exe 208 105312500
NTFSWatcher.exe 248 15625000
OmniAddrService.exe 268 86406250
pcas.exe 396 172187500
nssm.exe 696 2968750
    salt-minion.exe 716 79062500
salt-minion.exe 716 79062500
TeamViewer_Service.exe 772 172343750
winvnc4.exe 844 78750000
svchost.exe 880 151718750
explorer.exe 1452 7501250000
    TSVNCache.exe 2496 114531250
    ctfmon.exe 2540 82343750
    chrome.exe 2556 25053125000
    RocketDock.exe 2564 411406250
    Xshell.exe 5200 12957656250
    mstsc.exe 8468 227500000
    iexplore.exe 7672 13281250
    cmd.exe 9404 312500
    sublime_text.exe 8920 131093750
    notepad.exe 2248 1718750
TSVNCache.exe 2496 114531250
ctfmon.exe 2540 82343750
chrome.exe 2556 25053125000
    chrome.exe 3880 24531250
    chrome.exe 3872 52500000
    chrome.exe 2020 331093750
    chrome.exe 1028 35937500
    chrome.exe 196 37187500
    chrome.exe 184 55625000
    chrome.exe 2736 37656250
    chrome.exe 2752 1755781250
    chrome.exe 2772 83281250
    chrome.exe 2976 258125000
    SogouFlash.exe 3580 640468750
    SogouCloud.exe 3488 115625000
    SGImeGuard.exe 4300 24218750
    chrome.exe 3700 40312500
    chrome.exe 9148 3741406250
    chrome.exe 8496 7201250000
    chrome.exe 6840 200312500
    SogouSmartInfo.exe 9852 468750
RocketDock.exe 2564 411406250
alg.exe 3208 56093750
chrome.exe 3880 24531250
chrome.exe 3872 52500000
chrome.exe 2020 331093750
chrome.exe 1028 35937500
chrome.exe 196 37187500
chrome.exe 184 55625000
chrome.exe 2736 37656250
chrome.exe 2752 1755781250
chrome.exe 2772 83281250
chrome.exe 2976 258125000
TaobaoProtect.exe 3772 27562812500
conime.exe 388 59218750
SogouFlash.exe 3580 640468750
SogouCloud.exe 3488 115625000
SGImeGuard.exe 4300 24218750
Xshell.exe 5200 12957656250
chrome.exe 3700 40312500
aliwssv.exe 7160 46875000
TM.exe 9144 2396250000
chrome.exe 9148 3741250000
Alipaybsm.exe 9536 73593750
chrome.exe 8496 7199843750
mstsc.exe 8468 227500000
iexplore.exe 7672 13281250
    iexplore.exe 7256 148593750
iexplore.exe 7256 148437500
cmd.exe 9404 312500
    python.exe 9048 1875000
sublime_text.exe 8920 127968750
    plugin_host.exe 9840 32031250
plugin_host.exe 9840 30625000
    cmd.exe 6384 156250
python.exe 9048 1875000
notepad.exe 2248 1718750
chrome.exe 6840 200312500
SogouSmartInfo.exe 9852 468750
cmd.exe 6384 156250
    python.exe 9584 10312500
python.exe 9584 1093750
wmiprvse.exe 5184 781250

上面的从左到右分别是 进程名pid,cpu的运行时间

方式二:

import win32pdh, string, win32api
 
def procids():
    #each instance is a process, you can have multiple processes w/same name
    junk, instances = win32pdh.EnumObjectItems(None,None,'process', win32pdh.PERF_DETAIL_WIZARD)
    proc_ids=[]
    proc_dict={}
    for instance in instances:
        if instance in proc_dict:
            proc_dict[instance] = proc_dict[instance] + 1
        else:
            proc_dict[instance]=0
    for instance, max_instances in proc_dict.items():
        for inum in xrange(max_instances+1):
            hq = win32pdh.OpenQuery() # initializes the query handle 
            path = win32pdh.MakeCounterPath( (None,'process',instance, None, inum,'ID Process') )
            counter_handle=win32pdh.AddCounter(hq, path) 
            win32pdh.CollectQueryData(hq) #collects data for the counter 
            type, val = win32pdh.GetFormattedCounterValue(counter_handle, win32pdh.PDH_FMT_LONG)
            proc_ids.append((instance,str(val)))
            win32pdh.CloseQuery(hq) 
 
    proc_ids.sort()
    return proc_ids
 
print procids()

运行结果:

[(u'Alipaybsm', '9536'), (u'DhMachineSvc', '2040'), (u'GoogleUpdate', '208'), (u'Idle', '0'), (u'NTFSWatcher', '248'), (u'OmniAddrService', '268'), (u'RocketDock', '2564'), (u'SGImeGuard', '4300'), (u'SogouCloud', '3488'), (u'SogouFlash', '3580'), (u'SogouSmartInfo', '9852'), (u'System', '4'), (u'TM', '9144'), (u'TSVNCache', '2496'), (u'TaobaoProtect', '3772'), (u'TeamViewer_Service', '772'), (u'Xshell', '5200'), (u'_Total', '0'), (u'alg', '3208'), (u'aliwssv', '7160'), (u'chrome', '1028'), (u'chrome', '184'), (u'chrome', '196'), (u'chrome', '2020'), (u'chrome', '2556'), (u'chrome', '2736'), (u'chrome', '2752'), (u'chrome', '2772'), (u'chrome', '2976'), (u'chrome', '3700'), (u'chrome', '3872'), (u'chrome', '3880'), (u'chrome', '6840'), (u'chrome', '8496'), (u'chrome', '9148'), (u'cmd', '9404'), (u'cmd', '9776'), (u'conime', '388'), (u'csrss', '916'), (u'ctfmon', '2540'), (u'explorer', '1452'), (u'iexplore', '7256'), (u'iexplore', '7672'), (u'jqs', '200'), (u'lsass', '1044'), (u'mstsc', '8468'), (u'notepad', '2248'), (u'nssm', '696'), (u'pcas', '396'), (u'plugin_host', '9840'), (u'python', '3540'), (u'python', '9048'), (u'salt-minion', '716'), (u'services', '1024'), (u'smss', '864'), (u'spoolsv', '1860'), (u'sublime_text', '8920'), (u'svchost', '1236'), (u'svchost', '1304'), (u'svchost', '1480'), (u'svchost', '1524'), (u'svchost', '1636'), (u'svchost', '1688'), (u'svchost', '880'), (u'winlogon', '940'), (u'winvnc4', '844')]
[Finished in 0.3s]

获得 一个进程名进程Id元组的列表

方式三:

# http://code.activestate.com/recipes/305279/
 
"""
Enumerates active processes as seen under windows Task Manager on Win NT/2k/XP using PSAPI.dll
(new api for processes) and using ctypes.Use it as you please.
 
Based on information from http://support.microsoft.com/default.aspx?scid=KB;EN-US;Q175030&ID=KB;EN-US;Q175030
 
By Eric Koome
email ekoome@yahoo.com
license GPL
"""
from ctypes import *
 
#PSAPI.DLL
psapi = windll.psapi
#Kernel32.DLL
kernel = windll.kernel32
 
def EnumProcesses():
    arr = c_ulong * 256
    lpidProcess= arr()
    cb = sizeof(lpidProcess)
    cbNeeded = c_ulong()
    hModule = c_ulong()
    count = c_ulong()
    modname = c_buffer(30)
    PROCESS_QUERY_INFORMATION = 0x0400
    PROCESS_VM_READ = 0x0010
 
    #Call Enumprocesses to get hold of process id's
    psapi.EnumProcesses(byref(lpidProcess),
                        cb,
                        byref(cbNeeded))
 
    #Number of processes returned
    nReturned = cbNeeded.value/sizeof(c_ulong())
 
    pidProcess = [i for i in lpidProcess][:nReturned]
 
    for pid in pidProcess:
 
        #Get handle to the process based on PID
        hProcess = kernel.OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
                                      False, pid)
        if hProcess:
            psapi.EnumProcessModules(hProcess, byref(hModule), sizeof(hModule), byref(count))
            psapi.GetModuleBaseNameA(hProcess, hModule.value, modname, sizeof(modname))
            print "".join([ i for i in modname if i != '\x00'])
 
            #-- Clean up
            for i in range(modname._length_):
                modname[i]='\x00'
 
            kernel.CloseHandle(hProcess)
 
if __name__ == '__main__':
    EnumProcesses()

运行结果:

smss.exe
winlogon.exe
services.exe
lsass.exe
svchost.exe
svchost.exe
svchost.exe
spoolsv.exe
DhMachineSvc.exe
jqs.exe
GoogleUpdate.exe
NTFSWatcher.exe
OmniAddrService.exe
pcas.exe
nssm.exe
salt-minion.exe
TeamViewer_Service.exe
WinVNC4.exe
svchost.exe
Explorer.EXE
TSVNCache.exe
ctfmon.exe
chrome.exe
RocketDock.exe
chrome.exe
chrome.exe
chrome.exe
chrome.exe
chrome.exe
chrome.exe
chrome.exe
chrome.exe
chrome.exe
chrome.exe
TaobaoProtect.exe
conime.exe
SogouFlash.exe
SogouCloud.exe
SGImeGuard.exe
Xshell.exe
chrome.exe
aliwssv.exe
TM.exe
chrome.exe
Alipaybsm.exe
chrome.exe
mstsc.exe
iexplore.exe
iexplore.exe
cmd.exe
sublime_text.exe
plugin_host.exe
python.exe
NOTEPAD.EXE
chrome.exe
chrome.exe
SogouSmartInfo.exe
cmd.exe
python.exe

通过交互模式,使用WMI取得进程:

# http://mail.python.org/pipermail/python-win32/2003-December/001482.html
>>> import wmi
>>> processes = wmi.WMI().InstancesOf('Win32_Process')
>>> len(processes)
41
>>> [process.Properties_('Name').Value for process in processes] # get
the process names
[u'System Idle Process', u'System', u'SMSS.EXE', u'CSRSS.EXE',
u'WINLOGON.EXE', u'SERVICES.EXE', u'LSASS.EXE', u'SVCHOST.EXE',
u'SVCHOST.EXE', u'SVCHOST.EXE', u'SVCHOST.EXE', u'SPOOLSV.EXE',
u'ati2evxx.exe', u'BAsfIpM.exe', u'defwatch.exe', u'inetinfo.exe',
u'mdm.exe', u'rtvscan.exe', u'SCARDSVR.EXE', u'WLTRYSVC.EXE',
u'BCMWLTRY.EXE', u'EXPLORER.EXE', u'Apoint.exe', u'carpserv.exe',
u'atiptaxx.exe', u'quickset.exe', u'DSentry.exe', u'Directcd.exe',
u'vptray.exe', u'ApntEx.exe', u'FaxCtrl.exe', u'digstream.exe',
u'CTFMON.EXE', u'wuauclt.exe', u'IEXPLORE.EXE', u'Pythonwin.exe',
u'MMC.EXE', u'OUTLOOK.EXE', u'LineMgr.exe', u'SAPISVR.EXE',
u'WMIPRVSE.EXE']
 
# Here is how to get a single process and get its PID.
 
>>> p = wmi.WMI().ExecQuery('select * from Win32_Process where
Name="Pythonwin.exe"')
>>> [prop.Name for prop in p[0].Properties_] # let's look at all the
process property names
[u'Caption', u'CommandLine', u'CreationClassName', u'CreationDate',
u'CSCreationClassName', u'CSName', u'Description', u'ExecutablePath',
u'ExecutionState', u'Handle', u'HandleCount', u'InstallDate',
u'KernelModeTime', u'MaximumWorkingSetSize', u'MinimumWorkingSetSize',
u'Name', u'OSCreationClassName', u'OSName', u'OtherOperationCount',
u'OtherTransferCount', u'PageFaults', u'PageFileUsage',
u'ParentProcessId', u'PeakPageFileUsage', u'PeakVirtualSize',
u'PeakWorkingSetSize', u'Priority', u'PrivatePageCount', u'ProcessId',
u'QuotaNonPagedPoolUsage', u'QuotaPagedPoolUsage',
u'QuotaPeakNonPagedPoolUsage', u'QuotaPeakPagedPoolUsage',
u'ReadOperationCount', u'ReadTransferCount', u'SessionId', u'Status',
u'TerminationDate', u'ThreadCount', u'UserModeTime', u'VirtualSize',
u'WindowsVersion', u'WorkingSetSize', u'WriteOperationCount',
u'WriteTransferCount']
>>> p[0].Properties_('ProcessId').Value # get our ProcessId
928

方式四:

此方法可以跨平台,不过需要在安装psutil包.

import os
import psutil
import time
 
logPath = r'some\path\proclogs'
if not os.path.exists(logPath):
    os.mkdir(logPath)
 
separator = "-" * 80
format = "%7s %7s %12s %12s %30s, %s"
format2 = "%7.4f %7.2f %12s %12s %30s, %s"
while 1:
  # psutil.get_process_list() 方法已经废弃,可以使用psutil.process_iter()迭代器

    procs = psutil.get_process_list()
    procs = sorted(procs, key=lambda proc: proc.name)
 
    logPath = r'some\path\proclogs\procLog%i.log' % int(time.time())
    f = open(logPath, 'w')
    f.write(separator + "\n")
    f.write(time.ctime() + "\n")
    f.write(format % ("%CPU", "%MEM", "VMS", "RSS", "NAME", "PATH"))
    f.write("\n")
 
    for proc in procs:
        cpu_percent = proc.get_cpu_percent()
        mem_percent = proc.get_memory_percent()
        rss, vms = proc.get_memory_info()
        rss = str(rss)
        vms = str(vms)
        name = proc.name
        path = proc.path
        f.write(format2 % (cpu_percent, mem_percent, vms, rss, name, path))
        f.write("\n\n")
    f.close()
    print "Finished log update!"
    time.sleep(300)
    print "writing new log data!"

以上实现一个类似top的工具。

转自 http://www.blog.pythonlibrary.org/2010/10/03/how-to-find-and-list-all-running-processes-with-python/

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 214,922评论 6 497
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,591评论 3 389
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 160,546评论 0 350
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,467评论 1 288
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,553评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,580评论 1 293
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,588评论 3 414
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,334评论 0 270
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,780评论 1 307
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,092评论 2 330
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,270评论 1 344
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,925评论 5 338
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,573评论 3 322
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,194评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,437评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,154评论 2 366
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,127评论 2 352

推荐阅读更多精彩内容