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好像没有用到。

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