Python管理Windows进程
家电修理 2023-07-16 19:17www.caominkang.com电器维修
用python获得正在的运行的indos进程的有几种方式:
方式一通过 PyWin32包对Windos进行处理。
可以通过这个获取系统信息,但仅限于indos系统。
import in32.client mi=in32.client.GetObject('inmgmts:')for p in mi.InstancesOf('in32_process'): print p.Name, p.Properties_('ProcessId'), int(p.Properties_('UserModeTime').Value)+int(p.Properties_('KernelModeTime').Value) children=mi.ExecQuery('Select from in32_process here 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 14906718750System 4 14906718750 smss.exe 864 937500smss.exe 864 937500 csrss.exe 916 1752187500 inlogon.exe 940 72812500csrss.exe 916 1752187500inlogon.exe 940 72812500 services.exe 1024 324236406250 lsass.exe 1044 10099062500services.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 TeamVieer_Service.exe 772 172343750 invnc4.exe 844 78750000 svchost.exe 880 151718750 alg.exe 3208 56093750lsass.exe 1044 10099062500svchost.exe 1236 35468750 miprvse.exe 5184 2500000svchost.exe 1304 6174687500svchost.exe 1480 198943125000svchost.exe 1524 35156250svchost.exe 1636 1412656250svchost.exe 1688 494843750spoolsv.exe 1860 45312500DhMachineSvc.exe 2040 23593750jqs.exe 200 11605000000GoogleUpdate.exe 208 105312500NTFSWatcher.exe 248 15625000OmniAddrService.exe 268 86406250pcas.exe 396 172187500nssm.exe 696 2968750 salt-minion.exe 716 79062500salt-minion.exe 716 79062500TeamVieer_Service.exe 772 172343750invnc4.exe 844 78750000svchost.exe 880 151718750explorer.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 1718750TSVNCache.exe 2496 114531250ctfmon.exe 2540 82343750chrome.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 468750RocketDock.exe 2564 411406250alg.exe 3208 56093750chrome.exe 3880 24531250chrome.exe 3872 52500000chrome.exe 2020 331093750chrome.exe 1028 35937500chrome.exe 196 37187500chrome.exe 184 55625000chrome.exe 2736 37656250chrome.exe 2752 1755781250chrome.exe 2772 83281250chrome.exe 2976 258125000TaobaoProtect.exe 3772 27562812500conime.exe 388 59218750SogouFlash.exe 3580 640468750SogouCloud.exe 3488 115625000SGImeGuard.exe 4300 24218750Xshell.exe 5200 12957656250chrome.exe 3700 40312500alissv.exe 7160 46875000TM.exe 9144 2396250000chrome.exe 9148 3741250000Alipaybsm.exe 9536 73593750chrome.exe 8496 7199843750mstsc.exe 8468 227500000iexplore.exe 7672 13281250 iexplore.exe 7256 148593750iexplore.exe 7256 148437500cmd.exe 9404 312500 python.exe 9048 1875000sublime_text.exe 8920 127968750 plugin_host.exe 9840 32031250plugin_host.exe 9840 30625000 cmd.exe 6384 156250python.exe 9048 1875000notepad.exe 2248 1718750chrome.exe 6840 200312500SogouSmartInfo.exe 9852 468750cmd.exe 6384 156250 python.exe 9584 10312500python.exe 9584 1093750miprvse.exe 5184 781250
方式二上面的从左到右分别是 进程名,pid,cpu的运行时间
import in32pdh, string, in32api def procids(): #each instance is a process, you can have multiple processes /same name junk, instances = in32pdh.EnumObjectItems(None,None,'process', in32pdh.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 = in32pdh.OpenQuery() # initializes the query handle path = in32pdh.MakeCounterPath( (None,'process',instance, None, inum,'ID Process') ) counter_handle=in32pdh.AddCounter(hq, path) in32pdh.CollectQueryData(hq) #collects data for the counter type, val = in32pdh.GetFormattedCounterValue(counter_handle, in32pdh.PDH_FMT_LONG) proc_ids.append((instance,str(val))) in32pdh.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'TeamVieer_Service', '772'), (u'Xshell', '5200'), (u'_Total', '0'), (u'alg', '3208'), (u'alissv', '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'inlogon', '940'), (u'invnc4', '844')] [Finished in 0.3s]
方式三获得 一个进程名,进程Id元组的列表
# http://code.activestate./recipes/305279/ """ Enumerates active processes as seen under indos Task Manager on Win NT/2k/XP using PSAPI.dll (ne api for processes) and using ctypes.Use it as you please. based on information from http://support.microsoft./default.aspx?scid=KB;EN-US;Q175030&ID=KB;EN-US;Q175030 By Eric Koome email ekoome@yahoo. license GPL """from ctypes import #PSAPI.DLLpsapi = indll.psapi#Kernel32.DLLkernel = indll.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.exeinlogon.exeservices.exelsass.exesvchost.exesvchost.exesvchost.exespoolsv.exeDhMachineSvc.exejqs.exeGoogleUpdate.exeNTFSWatcher.exeOmniAddrService.exepcas.exenssm.exesalt-minion.exeTeamVieer_Service.exeWinVNC4.exesvchost.exeExplorer.EXETSVNCache.exectfmon.exechrome.exeRocketDock.exechrome.exechrome.exechrome.exechrome.exechrome.exechrome.exechrome.exechrome.exechrome.exechrome.exeTaobaoProtect.execonime.exeSogouFlash.exeSogouCloud.exeSGImeGuard.exeXshell.exechrome.exealissv.exeTM.exechrome.exeAlipaybsm.exechrome.exemstsc.exeiexplore.exeiexplore.execmd.exesublime_text.exeplugin_host.exepython.exeNOTEPAD.EXEchrome.exechrome.exeSogouSmartInfo.execmd.exepython.exe
通过交互模式,使用WMI取得进程
# http://mail.python./pipermail/python-in32/2003-December/001482.html>>> import mi>>> processes = mi.WMI().InstancesOf('Win32_Process')>>> len(processes)41>>> [process.Properties_('Name').Value for process in processes] # getthe 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'defatch.exe', u'iinfo.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'uauclt.exe', u'IEXPLORE.EXE', u'Pythonin.exe', u'MMC.EXE', u'OUTLOOK.EXE', u'LineMgr.exe', u'SAPISVR.EXE', u'WMIPRVSE.EXE'] # Here is ho to get a single process and get its PID. >>> p = mi.WMI().ExecQuery('select from Win32_Process here Name="Pythonin.exe"')>>> [prop.Name for prop in p[0].Properties_] # let's look at all theprocess 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'WindosVersion', u'WorkingSetSize', u'WriteOperationCount', u'WriteTransferCount']>>> p[0].Properties_('ProcessId').Value # get our ProcessId928方式四:
此方法可以跨平台,不过需要在安装psutil包.
import osimport psutilimport time logPath = r'somepathproclogs'if not os.path.exists(logPath): os.mkdir(logPath) separator = "-" 80format = "%7s %7s %12s %12s %30s, %s"format2 = "%7.4f %7.2f %12s %12s %30s, %s"hile 1: # psutil.get_process_list() 方法已经废弃,可以使用psutil.process_iter()迭代器 procs = psutil.get_process_list() procs = sorted(procs, key=lambda proc: proc.name) logPath = r'somepathproclogsprocLog%i.log' % int(time.time()) f = open(logPath, '') f.rite(separator + "n") f.rite(time.ctime() + "n") f.rite(format % ("%CPU", "%MEM", "VMS", "RSS", "NAME", "PATH")) f.rite("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.rite(format2 % (cpu_percent, mem_percent, vms, rss, name, path)) f.rite("nn") f.close() print "Finished log update!" time.sleep(300) print "riting ne log data!"
以上实现一个类似的工具。
转自 http://.blog.pythonlibrary./2010/10/03/ho-to-find-and-list-all-running-processes-ith-python/
上一篇:微信视频怎么设置铃声自定义?
下一篇:豹来电怎么开启自动启动权限 豹来电自动启动权
空调维修
- 海信电视维修站 海信电视维修站点
- 格兰仕空调售后电话 格兰仕空调维修售后服务电
- 家电售后服务 家电售后服务流程
- 华扬太阳能维修 华扬太阳能维修收费标准表
- 三菱电机空调维修 三菱电机空调维修费用高吗
- 美的燃气灶维修 美的燃气灶维修收费标准明细
- 科龙空调售后服务 科龙空调售后服务网点
- 华帝热水器维修 华帝热水器维修常见故障
- 康泉热水器维修 康泉热水器维修故障
- 华凌冰箱维修电话 华凌冰箱维修点电话
- 海尔维修站 海尔维修站点地址在哪里
- 北京海信空调维修 北京海信空调售后服务
- 科龙空调维修 科龙空调维修故障
- 皇明太阳能售后 皇明太阳能售后维修点
- 海信冰箱售后服务 海信冰箱售后服务热线电话
- 海尔热水器服务热线