我遇到了一些问题。我将尝试获取我机器上所有进程的所有模块(dll文件)。我试图在CMD中执行此命令:
tasklist /m
但这是64位系统的问题。如果您在64位计算机上运行32位程序,则不会列出所有模块,仅
ntdll.dll, wow64.dll, wow64win.dll, wow64cpu.dll
然后我尝试用Python脚本,使用pywin32(win32api)。
这是代码:
import win32security,win32file,win32api,ntsecuritycon,win32con,win32process
processes = win32process.EnumProcesses()
for pid in processes:
dll_list = []
try:
if pid:
print('pid:', pid)
ph = win32api.OpenProcess(win32con.MAXIMUM_ALLOWED, False, pid)
dll = win32process.EnumProcessModules(ph)
for dll_name in dll:
dll_name_norm = win32process.GetModuleFileNameEx(ph, dll_name)
dll_list.append(dll_name_norm)
print("dll_list: ", dll_list)
print("--------------")
except:
print("Error")
print("--------------")
但结果是一样的。 =( 请帮助我,我可以看到所有dll文件,每个进程加载。
P.S。它可能只是标准的Windows工具,如命令行,任务列表(NOT ListDlls,Process Explorer或相同的东西)或Python中的脚本。
非常感谢你!
答案 0 :(得分:4)
EnumProcessModules
只显示与Python相同的过程。而是使用dwFilterFlag=LIST_MODULES_ALL
致电EnumProcessModulesEx
。
您当前的代码需要win32api
模块,该模块只有recently added EnumProcessModulesEx
,而且不在标准库中。这是一个仅使用标准库的解决方案:
from ctypes import byref, create_unicode_buffer, sizeof, WinDLL
from ctypes.wintypes import DWORD, HMODULE, MAX_PATH
Psapi = WinDLL('Psapi.dll')
Kernel32 = WinDLL('kernel32.dll')
PROCESS_QUERY_INFORMATION = 0x0400
PROCESS_VM_READ = 0x0010
LIST_MODULES_ALL = 0x03
def EnumProcesses():
buf_count = 256
while True:
buf = (DWORD * buf_count)()
buf_size = sizeof(buf)
res_size = DWORD()
if not Psapi.EnumProcesses(byref(buf), buf_size, byref(res_size)):
raise OSError('EnumProcesses failed')
if res_size.value >= buf_size:
buf_count *= 2
continue
count = res_size.value // (buf_size // buf_count)
return buf[:count]
def EnumProcessModulesEx(hProcess):
buf_count = 256
while True:
buf = (HMODULE * buf_count)()
buf_size = sizeof(buf)
needed = DWORD()
if not Psapi.EnumProcessModulesEx(hProcess, byref(buf), buf_size,
byref(needed), LIST_MODULES_ALL):
raise OSError('EnumProcessModulesEx failed')
if buf_size < needed.value:
buf_count = needed.value // (buf_size // buf_count)
continue
count = needed.value // (buf_size // buf_count)
return map(HMODULE, buf[:count])
def GetModuleFileNameEx(hProcess, hModule):
buf = create_unicode_buffer(MAX_PATH)
nSize = DWORD()
if not Psapi.GetModuleFileNameExW(hProcess, hModule,
byref(buf), byref(nSize)):
raise OSError('GetModuleFileNameEx failed')
return buf.value
def get_process_modules(pid):
hProcess = Kernel32.OpenProcess(
PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
False, pid)
if not hProcess:
raise OSError('Could not open PID %s' % pid)
try:
return [
GetModuleFileNameEx(hProcess, hModule)
for hModule in EnumProcessModulesEx(hProcess)]
finally:
Kernel32.CloseHandle(hProcess)
for pid in EnumProcesses():
try:
dll_list = get_process_modules(pid)
print('dll_list: ', dll_list)
except OSError as ose:
print(str(ose))
print('-' * 14)