python:讓源碼更安全之將py編譯成so

來源:互聯網
上載者:User

標籤:and   .so檔案   copy   event   保護   高效   思路   對象   als   

應用情境

  Python是一種物件導向的解釋型電腦程式設計語言,具有豐富和強大的庫,使用其開發產品快速高效。

  python的解釋特性是將py編譯為專屬的二進位編碼pyc檔案,然後對pyc中的指令進行解釋執行,但是pyc的反編譯卻非常簡單,可直接反編譯為源碼,當需要將產品發布到外部環境的時候,源碼的保護尤為重要.

準備工作

  環境是可為linux/centos,我Windows10本地是Bash on Ubuntu on Windows,用起來很方便,命令列打bash即進入命令列

  思路是先將py轉換為c代碼,然後編譯c為so檔案

  所以要安裝以下內容

    python 安裝:cython

      pip install cython

    linux 安裝:python-devel,gcc

      yum install python-devel

      yum install gcc

 

初步編譯

  在testing檔案夾下有your_file.py檔案待編譯,內容如下

#-* -coding: UTF-8 -* -
__author__ = ‘Arvin‘class test: def say(self): print ‘hello‘

  建立setup.py,內容如下

from distutils.core import setupfrom Cython.Build import cythonizesetup(ext_modules = cythonize(["your_file.py"]))

  在bash中執行

cd testingpython setup.py build_ext

 

  運行後會產生build檔案夾,如下,lib.linux-x86_64-2.7下就是我們想要的.so檔案

  

  現在so檔案就可以像普通py檔案一樣匯入了

cd build/lib.linux-x86_64-2.7/pythonfrom your_file import testtest().say()

 

整合編譯

  最新代碼github:https://github.com/ArvinMei/py2so.git

  做了以下內容:

    1.檔案夾編譯

    2.刪除編譯出的.c檔案

    3.刪除編譯的temp檔案夾

#-* -coding: UTF-8 -* -__author__ = ‘Arvin‘import sys, os, shutil, timefrom distutils.core import setupfrom Cython.Build import cythonizestarttime = 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, ex:    print "error! ", ex.messageelse:    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‘
View Code

 

注意問題

  1.編譯後執行需要相同的python版本和編碼

  2.py中使用__file__內建變數的檔案編譯後調用時會出問題,暫時沒有解決,還需要使用pyc代替

  3.使用時注意許可權控制

 

轉載需註明出處:http://www.cnblogs.com/ke10/p/py2so.html

 

python:讓源碼更安全之將py編譯成so

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.