前情提要
之前由於項目的需要,需要我們將一部分“關鍵代碼”隱藏起來。
雖然Python 先天支持 將源代碼 編譯后 生成 xxx.pyc 文件,但是破解起來相當容易 -_-!!
於是搜羅到了另外一種方法,將關鍵的代碼文件/庫 轉換成 .so ,從而將其保護起來。
使用 Cython 保護代碼 ( 測試環境為:Ubuntu16.04 - LTS)
① 准備工作
1. 安裝 cython
pip install cython
2. 安裝 python-dev
sudo apt-get install python-dev
3. 安裝gcc
sudo apt-get install gcc
② 新建setup.py,內容如下
from distutils.core import setup from Cython.Build import cythonize setup(ext_modules = cythonize(["Train_predict.py"]))
③ 運行腳本 (注: 需要在Python 文件的同目錄下運行)
python setup.py build_ext
④ 運行腳本后,在當前目錄會生成一個 /build 子目錄
打開后,可以看到 .so 文件已經生成:
將 .so 文件拷貝到原來 .py 文件的目錄后,刪除 .py文件;測試: 在沒有修改任何調用程序源碼的情況下,在pythoncharm中已經無法找到 “Train_predict.py” 中函數的定義,但是卻可以正常的調用這個函數。
OK, 我們已經成功地將“關鍵代碼” 隱藏起來; 任務完成!!
最后,感謝大家的觀看,歡迎留言討論哦 :)
參考:
http://fengzheng369.blog.163.com/blog/static/7522097920161253407914
http://www.cnblogs.com/ke10/p/py2so.html
補充
今天在網上查了下資料,發現可以一次編譯多個.py文件為 .so
from distutils.core import setup from Cython.Build import cythonize #setup( #ext_modules = cythonize("Train_predict.py") #) setup( ext_modules = cythonize(["SCIPinterface.py", "normalize.py"]) )
我們注意到可以用 list 作為cythonize的參數來傳入,於是,這里嘗試着傳遞了2個新的Python源程序文件 ("SCIPinterface.py", "normalize.py")
生成對應的 .so 文件以及terminal如下所示:
Done ~~
叒 一次的補充
現在我們已經可以生成變異后的 .so 文件了,但是每次編譯生成的 臨時文件(例如.c)然后處理起來很麻煩!!, 於是發現了另一個好東西,這里搬運過來。 也感謝原文的作者為大家打來的福音!!
集成編譯
最新代碼github:https://github.com/ArvinMei/py2so.git
做了以下內容:
1.文件夾編譯
2.刪除編譯出的.c文件
3.刪除編譯的temp文件夾
#-* -coding: UTF-8 -* - __author__ = 'Arvin' """ 執行前提: 系統安裝python-devel 和 gcc Python安裝cython 編譯整個當前目錄: python py-setup.py 編譯某個文件夾: python py-setup.py BigoModel 生成結果: 目錄 build 下 生成完成后: 啟動文件還需要py/pyc擔當,須將啟動的py/pyc拷貝到編譯目錄並刪除so文件 """ 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, ex: print "error! ", ex.message 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'
這樣,我們就可以和麻煩的臨時文件 say goodbye 啦 ~~