「这是我参与2022首次更文挑战的第11天,活动详情查看:2022首次更文挑战」
python源码加密
加密方式
python源码加密得方式,目前网上流传的方式中,有以下几种方式:
- py转pyc
- 代码混淆
- py转so
py转pyc
这种方式直接使用python提供的工具compileall,这个工具可以直接进行编译。 优点:简单方便,平台兼容性好 缺点:有现成的反编译工具(python-uncompyle6),破解成本低
代码混淆
使用代码混淆库pyobfuscate, 优点:简单方便,兼容性好 缺点:只能对单个文件加密,代码结构不会发生变化,也能获取字节码,破解难度不大
py转so
使用Cython将py转为so文件Cython官方文档。
MAC OS环境下安装
首先需要安装python环境中的Cython,可以使用如下命令进行安装:
pip install Cython
另外还需要安装python-devel和gcc,macOS环境中,默认会安装好了这2款软件,检测如下:
(pkg) michaelkoo@MacBook pkg % gcc -v
Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/4.2.1
Apple clang version 11.0.0 (clang-1100.0.33.17)
Target: x86_64-apple-darwin19.6.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin
MacOS环境下的测试实例
生成测试so文件
在当前用户目录下新建kaka目录,在目录中新建tm.py文件,在文件中输入以下测试内容:
def t():
print('it is t method')
def k():
print('it is k method')
name=' t k'
编写setup.py文件,该文件包含以下内容:
#from setuptools import setup
from distutils.core import setup
from Cython.Build import cythonize
setup(name='KaKaHelper',version='1.0.1',py_modules=['koo'],description='A helper for KaKa',author='KaKa',author_email='jjkchen@foxmail.com',license='MIT',keywords='ka helper',install_requires=['scapy>=2.4.4','psutil>=5.8.0'],python_requires='>=3',ext_modules=cythonize(['tm.py']))
核心的是ext_modules模块,其他可以参考wheel打包方式的参数说明。
使用如下命令创建so文件:
python setup.py build_ext
编辑结果如下:
/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.7/lib/python3.7/distutils/dist.py:274: UserWarning: Unknown distribution option: 'install_requires'
warnings.warn(msg)
/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.7/lib/python3.7/distutils/dist.py:274: UserWarning: Unknown distribution option: 'python_requires'
warnings.warn(msg)
running build_ext
building 'kaka.tm' extension
creating build/temp.macosx-10.14-x86_64-3.7
xcrun -sdk macosx clang -arch x86_64 -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -iwithsysroot/System/Library/Frameworks/System.framework/PrivateHeaders -iwithsysroot/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.7/Headers -I/Users/michaelkoo/work/env/pkg/include -I/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.7/include/python3.7m -c tm.c -o build/temp.macosx-10.14-x86_64-3.7/tm.o
creating build/lib.macosx-10.14-x86_64-3.7
creating build/lib.macosx-10.14-x86_64-3.7/kaka
xcrun -sdk macosx clang -arch x86_64 -bundle -undefined dynamic_lookup build/temp.macosx-10.14-x86_64-3.7/tm.o -o build/lib.macosx-10.14-x86_64-3.7/kaka/tm.cpython-37m-darwin.so
从创建日志中,我们可以看到“build/lib.macosx-10.14-x86_64-3.7/kaka/tm.cpython-37m-darwin.so”, 创建一个so文件,我们进入对应目录查看是否存在这个文件:
(pkg) michaelkoo@MacBook kaka % pwd
/Users/michaelkoo/work/env/pkg/kaka/build/lib.macosx-10.14-x86_64-3.7/kaka
(pkg) michaelkoo@MacBook kaka % ls
tm.cpython-37m-darwin.so
目前是存在对应的so文件。
运行测试so文件
我们把上面创建的so文件复制到kaka根目录下,同时新建测试运行文件test.py
-rw-r--r-- 1 michaelkoo staff 37 3 26 12:43 test.py
-rwxr-xr-x 1 michaelkoo staff 33276 3 27 22:04 tm.cpython-37m-darwin.so
test.py文件中的内容如下:
from tm import *
print(name)
t()
k()
运行结果如下:
(pkg) michaelkoo@MacBook pkg % python test.py
t k
it is t method
it is k method
至此,python代码加密成so完成。
批量py文件转so文件操作
"""
much py to so
"""
import sys, os, shutil, time
from distutils.core import setup
from Cython.Build import cythonize
starttime = time.time()
setupfile = os.path.join(os.path.abspath('.'), __file__)
def getpy(basepath=os.path.abspath('.'), parentpath='', name='', build_dir="build",
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)
if os.path.isdir(ffile) and ffile != os.path.join(basepath, build_dir) and not fname.startswith('.'):
for f in getpy(basepath, os.path.join(parentpath, name), fname, build_dir, excepts, copyOther, delC):
yield f
elif os.path.isfile(ffile):
# print("\t", basepath, parentpath, name, 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 ext not in ('.pyc', '.pyx'):
# print("\t\t", basepath, parentpath, name, ffile)
if ext 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
if __name__ == "__main__":
currdir = os.path.abspath('.')
parentpath = sys.argv[1] if len(sys.argv) > 1 else "."
currdir, parentpath = os.path.split(currdir if parentpath == "." else os.path.abspath(parentpath))
build_dir = os.path.join(parentpath, "build")
build_tmp_dir = os.path.join(build_dir, "temp")
print("start:", currdir, parentpath, build_dir)
os.chdir(currdir)
try:
# 获取py列表
module_list = list(getpy(basepath=currdir, parentpath=parentpath, build_dir=build_dir, excepts=(setupfile)))
print(module_list)
setup(ext_modules=cythonize(module_list), script_args=["build_ext", "-b", build_dir, "-t", build_tmp_dir])
module_list = list(
getpy(basepath=currdir, parentpath=parentpath, build_dir=build_dir, excepts=(setupfile), copyOther=True))
except Exception as ex:
print("error! ", ex)
finally:
print("cleaning...")
module_list = list(
getpy(basepath=currdir, parentpath=parentpath, build_dir=build_dir, excepts=(setupfile), delC=True))
if os.path.exists(build_tmp_dir): shutil.rmtree(build_tmp_dir)
print("complete! time:", time.time() - starttime, 's')
将以上内容保存为much_so.py文件,然后运行如下:
python much_so.py /some/dir/
/some/dir是需要把py文件生成为so文件的所在目录。
Centos 7 环境下生成so文件
安装Cython
pip install Cython
安装成功后:
[root@php code]# pip list
backports.ssl-match-hostname (3.5.0.1)
configobj (4.7.2)
Cython (0.29.22)
decorator (3.4.0)
iniparse (0.4)
ipaddress (1.0.16)
IPy (0.75)
javapackages (1.0.0)
lxml (3.2.1)
perf (0.1)
pip (8.1.2)
policycoreutils-default-encoding (0.1)
pycurl (7.19.0)
pygobject (3.14.0)
pygpgme (0.3)
pyliblzma (0.5.3)
python-crontab (2.5.1)
python-dateutil (2.8.1)
pyudev (0.15)
pyxattr (0.5.1)
seobject (0.1)
sepolicy (1.1)
setuptools (0.9.8)
six (1.15.0)
slip (0.4.0)
slip.dbus (0.4.0)
urlgrabber (3.10)
yum-metadata-parser (1.1.4)
编写测试代码
步骤一:
# 编辑 outself.py
def tmp():
print('it is tmp method')
步骤二:
#编辑 setup.py
from distutils.core import setup
from Cython.Build import cythonize
setup(ext_modules=cythonize(['outself.py']))
生成so文件
运行以下命令生成so文件
python setup.py build_ext
编译成功后:
running build_ext
building 'outself' extension
gcc -pthread -fno-strict-aliasing -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -fPIC -I/usr/include/python2.7 -c outself.c -o build/temp.linux-x86_64-2.7/outself.o
creating build/lib.linux-x86_64-2.7
gcc -pthread -shared -Wl,-z,relro build/temp.linux-x86_64-2.7/outself.o -L/usr/lib64 -lpython2.7 -o build/lib.linux-x86_64-2.7/outself.so
编译完成后,会在当前目录下生产outself.c文件, 同时会在当前目录下生成build文件夹,其中里面就包含我们需要的so文件
build outself.c outself.py setup.py
异常记录
outself.c:16:20: 致命错误:Python.h:没有那个文件或目录
解决方案:安装python对应的开发工具
yum -y install python-devel