Python管理Windows进程

字数1936 阅读1650 评论0 喜欢5

用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 11055150937500System Idle Process 0 11055150937500System 4 14906718750
System 4 14906718750smss.exe 864 937500
smss.exe 864 937500csrss.exe 916 1752187500winlogon.exe 940 72812500
csrss.exe 916 1752187500
winlogon.exe 940 72812500services.exe 1024 324236406250lsass.exe 1044 10099062500
services.exe 1024 324236406250svchost.exe 1236 35468750svchost.exe 1304 6174687500svchost.exe 1480 198943593750svchost.exe 1524 35156250svchost.exe 1636 1412656250svchost.exe 1688 494843750spoolsv.exe 1860 45312500DhMachineSvc.exe 2040 23593750jqs.exe 200 11605000000NTFSWatcher.exe 248 15625000OmniAddrService.exe 268 86406250pcas.exe 396 172187500nssm.exe 696 2968750TeamViewer_Service.exe 772 172343750winvnc4.exe 844 78750000svchost.exe 880 151718750alg.exe 3208 56093750
lsass.exe 1044 10099062500
svchost.exe 1236 35468750wmiprvse.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 2968750salt-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 7501250000TSVNCache.exe 2496 114531250ctfmon.exe 2540 82343750chrome.exe 2556 25053125000RocketDock.exe 2564 411406250Xshell.exe 5200 12957656250mstsc.exe 8468 227500000iexplore.exe 7672 13281250cmd.exe 9404 312500sublime_text.exe 8920 131093750notepad.exe 2248 1718750
TSVNCache.exe 2496 114531250
ctfmon.exe 2540 82343750
chrome.exe 2556 25053125000chrome.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 258125000SogouFlash.exe 3580 640468750SogouCloud.exe 3488 115625000SGImeGuard.exe 4300 24218750chrome.exe 3700 40312500chrome.exe 9148 3741406250chrome.exe 8496 7201250000chrome.exe 6840 200312500SogouSmartInfo.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 13281250iexplore.exe 7256 148593750
iexplore.exe 7256 148437500
cmd.exe 9404 312500python.exe 9048 1875000
sublime_text.exe 8920 127968750plugin_host.exe 9840 32031250
plugin_host.exe 9840 30625000cmd.exe 6384 156250
python.exe 9048 1875000
notepad.exe 2248 1718750
chrome.exe 6840 200312500
SogouSmartInfo.exe 9852 468750
cmd.exe 6384 156250python.exe 9584 10312500
python.exe 9584 1093750
wmiprvse.exe 5184 781250

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

方式二:

import win32pdh, string, win32apidef procids():#each instance is a process, you can have multiple processes w/same namejunk, 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] + 1else:proc_dict[instance]=0for 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_idsprint 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;Q175030By Eric Koome
email ekoome@yahoo.com
license GPL
"""
from ctypes import *#PSAPI.DLL
psapi = windll.psapi
#Kernel32.DLL
kernel = windll.kernel32def EnumProcesses():arr = c_ulong * 256lpidProcess= arr()cb = sizeof(lpidProcess)cbNeeded = c_ulong()hModule = c_ulong()count = c_ulong()modname = c_buffer(30)PROCESS_QUERY_INFORMATION = 0x0400PROCESS_VM_READ = 0x0010#Call Enumprocesses to get hold of process id'spsapi.EnumProcesses(byref(lpidProcess),cb,byref(cbNeeded))#Number of processes returnednReturned = cbNeeded.value/sizeof(c_ulong())pidProcess = [i for i in lpidProcess][:nReturned]for pid in pidProcess:#Get handle to the process based on PIDhProcess = 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 upfor 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 timelogPath = 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.namepath = proc.pathf.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/

Python管理Windows进程相关推荐

  1. PowerShell 2.0 实践(四)管理Windows进程

    上一次我们对Windows服务进行了简单的管理,学习了获取本地及远程计算机上服务的方法,以及查找特定服务,开始.结束.暂停.恢复服务等操作.本次我们来关注一下Windows管理中另一个核心内容:进程管 ...

  2. python 管理windows客户端_在远程windows客户端上执行python脚本

    我正在使用paramiko在远程windows服务器上执行命令.我能够执行dir之类的命令并提取输出,但是执行python脚本似乎失败了.不会引发错误消息.在 下面是我的代码片段:def ssh_co ...

  3. python 管理windows客户端_scrapyd的Windows管理客户端|python基础教程|python入门|python教程...

    https://www.xin3721.com/eschool/pythonxin3721/ ScrapydManage GitHub地址:https://github.com/kanadebliss ...

  4. python windows系统管理_利用Python脚本管理Windows服务

    Windows服务常用的功能就是启动服务,关闭服务,重启服务和查询服务运行状态,其中查询服务运行状态是其他三种操作的基础. 本文中提到的使用Python脚本管理Windows服务实际上是调用win32 ...

  5. python写一个服务_写一个Python的windows服务

    1. 安装pywin32和pyinstaller pip install pywin32 pip install pyinstaller 2.写一个服务Demo # -*- coding: utf-8 ...

  6. python控制系统进程_python 监控windows进程

    python os.startfile python实现双击运行程序 python监控windows程序 监控进程不在时重新启动 用python监控您的window服务 原创作品,允许转载,转载时请务 ...

  7. Python实现的进程管理神器——Supervisor

    文章目录 常用命令 简介 安装 创建配置文件 开机自启 初试 Web 界面 配置文件 子进程配置模板 可用变量 supervisorctl 命令 Supervisor 组件 卸载 遇到的坑 参考文献 ...

  8. windows进程管理器_软件进程自动重启一遍又一遍……你需要这款自动杀进程的小公举ProcessKO...

    [PConline 应用]用Windows系统最烦的一件事,就是各种乱七八糟的进程.我们知道软件要运行,就会在后台唤起进程,但这些进程有时候并不那么听话,某些软件会不断唤起进程,对此Windows自带 ...

  9. Windows进程与线程学习笔记(七)—— 时间片管理

    Windows进程与线程学习笔记(七)-- 时间片管理 要点回顾 基本概念 CPU时间片 分析 KeUpdateRunTime 分析 KiDispatchInterrupt 备用线程 总结 要点回顾 ...

最新文章

  1. 背包问题概述(Lintcode- 562.Backpack IV问题解决)
  2. LA3989女士的选择
  3. find your place
  4. VS 中配置使用Visual SVN系列 五:SVN Client的配置和使用
  5. 教育场景下的实时音频解决方案
  6. TDD代码驱动测试基础
  7. 最全Pycharm教程
  8. 【Vue】—处理边界情况
  9. 还在低效搬砖?看 BIM 如何颠覆了土木工程?
  10. java虚拟机手动内存分配_《深入理解java虚拟机》-垃圾收集器与内存分配策略
  11. OpenGL+VS2012环境搭建
  12. python基础教程电子版-Python基础教程(第2版)PDF文档下载
  13. 如何在html中写json格式数据类型,html中如何美化展示json格式数据
  14. navicat 导入excel 闪退
  15. 双系统卸载ubuntu
  16. 阿里hotfix热修复自动更新,了解一下。
  17. QQ另存为出现“你没有权限在此位置中保存文件,请与管理员联系以获得相应权限”
  18. [原创]Win7SP1的映像DISM集成+kb3125574,打造Win7SP2
  19. ex计算机绘图基础教程怎么画图,cad制图速度小技巧,求习惯性的。实际操作的,快捷键 要最有配合价值的!感谢同仁。。。...
  20. 高考数学95分能学计算机吗,你知道马云高考数学考了多少分吗?

热门文章

  1. 前端开发培训机构哪家好
  2. k线分析中的量化测试方法_k线分析中如何使用量化思维案例分析
  3. php session 功能,php4的session功能评述(二)
  4. 7-148 亲和数判断
  5. 个人收藏之 - 一些网站
  6. Android动画(一)
  7. 创业公司如何分配股份与期权
  8. 在一家公司待久了没有目标,没有动力,我该怎么办?
  9. Android 阿里推送正常推送以及辅助通道走过的坑,字节跳动+阿里+华为+腾讯等大厂Android面试题
  10. 使用GraceNote Web API开发Mac查询音乐信息应用