使用pefile module顯示執行檔案所需要的DLL

最近才發現原來Python有一個可以讀取Portable Executable格式的module pefile[1]。於是就拿來練習,寫了一個可以顯示執行檔所需要的DLL的小程式。

     #!/usr/bin/env python
     # coding: utf-8
     """ showdll.py: show the depedency of given exeutable file. """

     import sys
     from os import path

     import pefile

     def get_depend(filename, dll_list=[]):
     """Return the dependency in hierarchical dictionary."""
     if not path.isfile(filename):
     return
     pe_obj = pefile.PE(filename, fast_load=True)
     pe_obj.parse_data_directories()
     dlls = {}
     if hasattr(pe_obj, 'DIRECTORY_ENTRY_IMPORT'):
     curr_dependency = []
     for entry in pe_obj.DIRECTORY_ENTRY_IMPORT:
     if entry.dll not in dll_list:
     dll_list.append(entry.dll)
     curr_dependency.append(entry.dll)
     for entry in curr_dependency:
     dlls[entry] = get_depend(entry, dll_list)
     return dlls

     def print_depend(dependency, depth=0, padding='\t'):
     prepend = padding * depth
     for k,v in dependency.items():
     print "%s%s" % (prepend, k)
     if isinstance(v, dict):
     print_depend(v, depth+1, padding)

     if __name__ == '__main__':
     dependency = get_depend(sys.argv[1])
     print_depend(dependency)
     Usage:
     > showdll.py foo.exe

Ref: https://code.google.com/p/pefile/

comments powered by Disqus