Skip to content

Instantly share code, notes, and snippets.

@htv2012
Last active April 13, 2018 22:36
Show Gist options
  • Save htv2012/a961f6310216ddf9a8d8edd324a42613 to your computer and use it in GitHub Desktop.
Save htv2012/a961f6310216ddf9a8d8edd324a42613 to your computer and use it in GitHub Desktop.
Find out which process is using a specific DLL
#!/usr/bin/env python
from __future__ import print_function, unicode_literals
import os
import re
import subprocess
"""
Sample listdlls output:
ListDLLs v3.1 - List loaded DLLs
Copyright (C) 1997-2011 Mark Russinovich
Sysinternals - www.sysinternals.com
------------------------------------------------------------------------------
lsass.exe pid: 1396
Command line: C:\WINDOWS\system32\lsass.exe
Base Size Path
0x00000000158f0000 0x11000 C:\WINDOWS\system32\lsass.exe
0x00000000bc450000 0x1d2000 C:\WINDOWS\SYSTEM32\ntdll.dll
0x00000000ba620000 0xac000 C:\WINDOWS\System32\KERNEL32.DLL
0x00000000b9480000 0x21d000 C:\WINDOWS\System32\KERNELBASE.dll
...
------------------------------------------------------------------------------
svchost.exe pid: 1564
Command line: C:\WINDOWS\system32\svchost.exe -k DcomLaunch
Base Size Path
0x00000000e1b80000 0xe000 C:\WINDOWS\system32\svchost.exe
0x00000000bc450000 0x1d2000 C:\WINDOWS\SYSTEM32\ntdll.dll
0x00000000ba620000 0xac000 C:\WINDOWS\System32\KERNEL32.DLL
0x00000000b9480000 0x21d000 C:\WINDOWS\System32\KERNELBASE.dll
0x00000000ba790000 0x59000 C:\WINDOWS\System32\sechost.dll
...
"""
def get_all_dlls():
"""
A generator to yield a list of tuples: (module, dll, dll_path), e.g.
('listdlls64.exe', 'ntdll.dll\r', 'C:\\WINDOWS\\SYSTEM32\\ntdll.dll\r')
"""
pattern = re.compile(r'^\w+\s+\w+\s+(.+)$')
output = subprocess.check_output(['listdlls.exe'])
lines = output.splitlines()
for line in lines:
if 'pid:' in line:
# lsass.exe pid: 1396
process = line.split()[0]
elif line.startswith('0x'):
# 0x00000000e1b80000 0xe000 C:\WINDOWS\system32\svchost.exe
# ==> module=svchost.exe, path=C:\WINDOWS\system32\svchost.exe
matched = pattern.match(line)
if matched:
path = matched.group(1)
filename = os.path.basename(path)
yield process, filename, path
if __name__ == '__main__':
target = 'tabdoc.dll'
for module, dll, dll_path in get_all_dlls():
# print((module, dll, dll_path))
if dll == target:
print('{}, {}'.format(module, dll))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment