Contents
枚举M$当前进程和端口
{{{Sean Lu <voidclass@gmail.com> reply-to python-cn@googlegroups.com, to python-cn@googlegroups.com, date Tue, Apr 8, 2008 at 9:21 AM subject [CPyUG:46317] Re: 有没有什么模块可以枚举windows当前的进程和当前开了哪些端口? }}}
Toggle line numbers
1 """
2 Enumerates active processes as seen under windows Task Manager on Win
3 NT/2k/XP using PSAPI.dll
4 (new api for processes) and using ctypes.Use it as you please.
5
6 Based on information from
7 http://support.microsoft.com/default.aspx?scid=KB;EN-US;Q175030&ID=KB;EN-US;Q175030
8
9 By Eric Koome
10 email ekoome@yahoo.com
11 license GPL
12 """
13 from ctypes import *
14
15 #PSAPI.DLL
16 psapi = windll.psapi
17 #Kernel32.DLL
18 kernel = windll.kernel32
19
20 def EnumProcesses():
21 arr = c_ulong * 256
22 lpidProcess= arr()
23 cb = sizeof(lpidProcess)
24 cbNeeded = c_ulong()
25 hModule = c_ulong()
26 count = c_ulong()
27 modname = c_buffer(30)
28 PROCESS_QUERY_INFORMATION = 0x0400
29 PROCESS_VM_READ = 0x0010
30
31 #Call Enumprocesses to get hold of process id's
32 psapi.EnumProcesses(byref(lpidProcess),
33 cb,
34 byref(cbNeeded))
35
36 #Number of processes returned
37 nReturned = cbNeeded.value/sizeof(c_ulong())
38
39 pidProcess = [i for i in lpidProcess][:nReturned]
40
41 for pid in pidProcess:
42
43 #Get handle to the process based on PID
44 hProcess = kernel.OpenProcess(PROCESS_QUERY_INFORMATION |PROCESS_VM_READ,
45 False, pid)
46 if hProcess:
47 psapi.EnumProcessModules(hProcess, byref(hModule),sizeof(hModule), byref(count))
48 psapi.GetModuleBaseNameA(hProcess, hModule.value, modname,sizeof(modname))
49 print "".join([ i for i in modname if i != '\x00'])
50
51 #-- Clean up
52 for i in range(modname._length_):
53 modname[i]='\x00'
54
55 kernel.CloseHandle(hProcess)
56
57 if __name__ == '__main__':
58 EnumProcesses()
反馈
创建 by -- ZoomQuiet [2008-04-08 01:28:09]