python打包若干個文件成so文件

目的:使用python把單個py文件或指定目錄裏面所有的py文件打包成so文件,以起到加密作用。
環境:ubuntu 16.04 64位系統,python2,安裝cython,gcc
安裝:

  • 安裝cython :sudo pip install cython
  • 安裝gcc: sudo apt-get install gcc

一、把單個py文件test.py打包成so文件。

  1. test.py代碼如下:

       # -*- coding:utf-8 -*- 
       	def hello(): 		
       	prin("hello world!")  
    

    setup.py代碼如下:

    # -*- coding:utf-8 -*- 
    from distutils.core import setup 
    from Cython.Build import cythonize
    
    setup( ext_modules = cythonize("test.py") )
    

    init.py文件代碼爲空,只是表明當前該目錄爲模塊目錄,以後導入so文件時會用到:

  2. 開始進行編譯打包成so文件,存放到當前目錄:python2 setup.py build_ext
    –inplace,inplace參數表示存放在當前目錄 在這裏插入圖片描述
    生成so文件,沒有在build目錄裏面,而是在新生成的和包目錄相同的目錄裏面。
    在這裏插入圖片描述

  3. 此時使用objdump -S test.so,儘可能反彙編出源代碼(關於objdump命令使用可點擊該處查看)。
    在這裏插入圖片描述
    在有註釋的地方要留意,可查看到test.py文件源代碼,
    在這裏插入圖片描述

二、打包指定目錄裏面的所有py文件,生成so文件。

  1. 將需要編譯的目錄d(d目錄有test1.py和test2.py)和setup.py放在同一層級,執行python setup.py,代碼如下:

    test1.py代碼如下:

    # -*- coding:utf-8 -*-
    def hello():
    	print("hello world!") 
    
    

    test2.py代碼如下:

    # -*- coding:utf-8 -*-
    def hello2():
    	print("hello world2!") 
    
    

    setup.py代碼如下(此處代碼來源於網絡):

    # -*- coding:utf-8 -*-
    import sys, os, shutil, time
    from distutils.core import setup
    from Cython.Build import cythonize
    
    starttime = time.time()
    currdir = os.path.abspath('.')
    parentpath = sys.argv[1] if len(sys.argv)>1 else ""
    setupfile= os.path.join(os.path.abspath('.'), __file__)
    build_dir = "build"
    build_tmp_dir = build_dir + "/temp"
    
    def getpy(basepath=os.path.abspath('.'), parentpath='', name='', excepts=(), copyOther=False,delC=False):
        """
        獲取py文件的路徑
        :param basepath: 根路徑
        :param parentpath: 父路徑
        :param name: 文件/夾
        :param excepts: 排除文件
        :param copy: 是否copy其他文件
        :return: py文件的迭代器
        """
        fullpath = os.path.join(basepath, parentpath, name)
        for fname in os.listdir(fullpath):
            ffile = os.path.join(fullpath, fname)
            #print basepath, parentpath, name,file
            if os.path.isdir(ffile) and fname != build_dir and not fname.startswith('.'):
                for f in getpy(basepath, os.path.join(parentpath, name), fname, excepts, copyOther, delC):
                    yield f
            elif os.path.isfile(ffile):
                ext = os.path.splitext(fname)[1]
                if ext == ".c":
                    if delC and os.stat(ffile).st_mtime > starttime:
                        os.remove(ffile)
                elif ffile not in excepts and os.path.splitext(fname)[1] not in('.pyc', '.pyx'):
                    if os.path.splitext(fname)[1] in('.py', '.pyx') and not fname.startswith('__'):
                        yield os.path.join(parentpath, name, fname)
                    elif copyOther:
                            dstdir = os.path.join(basepath, build_dir, parentpath, name)
                            if not os.path.isdir(dstdir): os.makedirs(dstdir)
                            shutil.copyfile(ffile, os.path.join(dstdir, fname))
            else:
                pass
    
    #獲取py列表
    module_list = list(getpy(basepath=currdir,parentpath=parentpath, excepts=(setupfile)))
    try:
        setup(ext_modules = cythonize(module_list),script_args=["build_ext", "-b", build_dir, "-t", build_tmp_dir])
    except Exception as e:
        print (e)
    else:
        module_list = list(getpy(basepath=currdir, parentpath=parentpath, excepts=(setupfile), copyOther=True))
    module_list = list(getpy(basepath=currdir, parentpath=parentpath, excepts=(setupfile), delC=True))
    if os.path.exists(build_tmp_dir): shutil.rmtree(build_tmp_dir)
    print ("complate! time:", time.time()-starttime, 's')
    
    
  2. 開始把d目錄裏面的py文件,打包編譯生成so文件
    在這裏插入圖片描述
    但是此時使用objdump -S test1.so,卻沒能發現源文件名及代碼內容。

總結:對一個py文件打包是可以查看到該文件源碼內容,但對指定的文件夾內所有的py文件打包,卻不能看到每個文件的源碼內容。另外,發現安裝gcc好像沒有用到。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章