本方法适用于Linux环境下:
1.安装库Cython
1 | pip3 install Cython==3.0.0a10 |
2.编写待加密文件:hello.py
1 2 3 4 5 6 7 8 | import randomdef ac(): i = random.randint(0, 5) if i > 2: print('success') else: print('failure') |
3.编写加密脚本
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | import osimport globfrom distutils.core import setupfrom Cython.Build import cythonize# 需要加密py文件所在文件夹,批量加密path_list = ["/opt/test/te", "/opt/test"]# 需要去除的py文件reduce_list = ["setup.py"]py_files = []for path in path_list: for root, dirs, files in os.walk(path): for file in glob.glob(os.path.join(root, "*.py")): for rds in reduce_list: if rds not in file: py_files.append(file)setup(ext_modules=cythonize(py_files), language_level=3) |
4.执行加密命令
1 | python3 setup.py build_ext --inplace |
5.执行结果:会生成build文件夹、同名.c文件和同名.so文件,其中.so文件是我们需要的文件,只保留.so文件,其余的全部删除
生成的文件名为 hello.cpython-38-x86_64-linux-gnu.so 可以把他重命名为hello.so, 只要保证跟原文件同名,且为.so格式即可
6.使用方式:与Python导包保持一致 from hello import ac
安全性:.so文件反编译后变成c语言,几乎不容易再变回原来的python代码。