跳到主要內容

使用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
[1]: https://code.google.com/p/pefile/

留言

這個網誌中的熱門文章

Portable Python

我常常需要把Python寫的script帶到其他電腦使用,因此,一個免安裝,可攜帶的Python就顯得十分重要。最近看過了幾個可攜式Python的方案,下面這個PortablePython是我覺得最合我意的方案。因為它提供了大部分會用到的Python module及工具,甚至連wxPython及PyGame也有。同時也有好用的Python編輯器PyScripter。所有開發Python所需的開發工具都一應俱全了!把它放到隨身碟中,就不用到處幫人安裝Python了。 PortablePython : http://www.portablepython.com/

一個Python程式可幫檔名加上日期與時間

很多時候,我們希望能夠將檔案或是目錄名稱加上一個時間及日期,以便release。所以,我就寫了一個小小的程式來達到這個目的。我把這個程式貼上來,讓有興趣的人可以拿去使用。 -- #!/usr/bin/env python # -*- coding: ascii -*- """ Usage: cfgfn.py [filename or directory list] """ import sys import os import time import re import glob ro = re.compile(r'(?P<FN> .*)-[0-9]{8}-[0-9]{4}(?P<EXT> .*)') for fnl in sys.argv[1:]: for fn in glob.glob(fnl): mo = ro.match(fn) if mo: pre = mo.group('FN') ext = mo.group('EXT') else: pre, ext = os.path.splitext(fn) newFn = pre + time.strftime('-%Y%m%d-%H%M') + ext os.rename(fn, newFn) print 'Rename %s -> %s' % (fn, newFn)