python --pyarmor代码加密(源代码)
·
安装
pip install pyarmor==9.1.7
示例:

控制台执行: pyarmor gen tools.py
会生成一个dist目录和新的当前文件 直接运行即可
加密整个文件夹
pyarmor gen -r 项目路径
多次使用同一个密钥加密
# pyarmor==9.2.3 python3.10.3
# 1. 创建输出目录
mkdir dist
# 2. 生成共享 runtime 包(核心步骤)
pyarmor gen runtime --output dist/shared_runtime
# 3. 加密入口文件(引用共享 runtime)
pyarmor gen --use-runtime dist/shared_runtime -O dist manage.py
# 4. 加密子目录文件(引用同一个共享 runtime)
pyarmor gen --use-runtime dist/shared_runtime -O dist/front_end front_end/views.py
# 5. 验证运行
cd dist
python manage.py
云编译加密to_pyc
server.py
服务端
# coding=utf-8
# @Time : 2025/7/9 8:34
# @Author : XiaoYi
# @Email: 1206154726@qq.com
# @Filename: server
import compileall
import time
import tqdm
from loguru import logger
from fastapi import FastAPI, Request, UploadFile, File
from starlette.middleware.cors import CORSMiddleware
from pathlib import Path
import uvicorn
import subprocess
import shutil
from starlette.responses import FileResponse
app = FastAPI()
BASE_DIR = Path(__file__).parent
CACHE_PY = BASE_DIR.joinpath('cache.py') # 暂存py文件
CACHE_PYC = BASE_DIR.joinpath('cache.pyc') # 暂存的pyc文件
PYARMOR = r'D:\code\ceshi\venv\Scripts\pyarmor.exe' # 加密的文件路径(替换成自己的)
SHARED_RUNTIME = BASE_DIR.joinpath('shared_runtime') # 共享文件库
app.add_middleware( # 跨域
CORSMiddleware,
allow_origins=["*", ],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
def start_cmd(cmd: list):
'''执行命令'''
response = subprocess.Popen(cmd, stdout=subprocess.PIPE, encoding='gb2312')
response1 = response.stdout.read()
return response1
def init_object():
'''初始化项目'''
run_time_file_set = ['.pyarmor.ikey',
'pyarmor_runtime_000000',
'pyarmor_runtime.pyd',
'__init__.py'] # 加密文件中应该存在的文件
now_file_set = [i.name for i in SHARED_RUNTIME.rglob('*')] # 实际存在的文件
diff = list(set(run_time_file_set) ^ set(now_file_set)) # 取差集
if diff:
logger.warning(f'系统中加密库不全或无加密共享库,重新创建【{SHARED_RUNTIME}】')
if SHARED_RUNTIME.exists():
shutil.rmtree(SHARED_RUNTIME)
cmd = [
f'{PYARMOR}',
f'gen',
f'runtime',
f'-O',
f'{SHARED_RUNTIME}'
]
start_cmd(cmd)
logger.success(f'共享加密库已创建成功~')
def pack_pyc_file():
'''编译单个文件'''
compileall.compile_file(
fullname=CACHE_PY, # 必选:单个文件的完整路径
force=True, # 强制重新编译
optimize=2, # 最高优化级别
quiet=0,
legacy=True
)
logger.debug(f'编译pyc【{CACHE_PY}】成功!')
@app.post("/compile")
async def compile(file: UploadFile = File(...)):
'''加密文件'''
logger.warning(f'图片保存地址:【{CACHE_PY}】')
with open(str(CACHE_PY), 'wb') as f:
for i in iter(lambda: file.file.read(512), b''):
f.write(i)
start_cmd([
f'{PYARMOR}',
f'gen',
f'--use-runtime',
f'{SHARED_RUNTIME}',
f'-O',
f'{CACHE_PY.parent}',
f'{CACHE_PY}'
])
for item in tqdm.tqdm([1, 2, 3]):
time.sleep(1)
pack_pyc_file()
for item in tqdm.tqdm([1, 2, 3]):
time.sleep(0.3)
return FileResponse(
path=CACHE_PYC,
filename=CACHE_PYC.name, # 下载时显示的文件名(可选)
media_type='application/octet-stream',
)
if __name__ == '__main__':
init_object()
uvicorn.run(app, host='127.0.0.1', port=8001, workers=1)
fastapi==0.103.2
loguru==0.7.3
Pillow==9.5.0
pyarmor==9.2.3
python-multipart==0.0.8
requests==2.31.0
starlette==0.27.0
tqdm==4.67.1
uvicorn==0.22.0
客户端
from pathlib import Path
from loguru import logger
import requests
class Compile(object):
'''编译'''
def __init__(self):
self.url = 'http://60.204.142.113:8010/compile'
self._desk_top = Path.home().joinpath("Desktop")
def save_file(self, response, name):
'''保存文件'''
file_abs_path = self._desk_top.joinpath(f'{name}.pyc')
with open(file_abs_path, 'wb') as f:
f.write(response)
logger.success(f'编译成功:【{file_abs_path}】')
def start(self, file_path):
'''开始编译'''
logger.debug(f'开始云编译;【{file_path}】')
filename = Path(file_path).name
with open(file_path, 'rb') as f:
file = f.read()
response = requests.post(self.url, files={"file": (filename, file)}).content
name = Path(file_path).stem
self.save_file(response, name)
if __name__ == '__main__':
a = Compile()
a.start(r'D:\code\huanqinglvyou\backstage\models.py')
云加密 to_py
server
# coding=utf-8
# @Time : 2025/7/9 8:34
# @Author : XiaoYi
# @Email: 1206154726@qq.com
# @Filename: server
import time
import tqdm
from loguru import logger
from fastapi import FastAPI, Request, UploadFile, File
from starlette.middleware.cors import CORSMiddleware
from pathlib import Path
import uvicorn
import subprocess
import shutil
from starlette.responses import FileResponse
app = FastAPI()
BASE_DIR = Path(__file__).parent
CACHE_PY = BASE_DIR.joinpath('cache.py') # 暂存py文件
PYARMOR = r'D:\code\ceshi\venv\Scripts\pyarmor.exe' # 加密的文件路径
SHARED_RUNTIME = BASE_DIR.joinpath('shared_runtime') # 共享文件库
app.add_middleware( # 跨域
CORSMiddleware,
allow_origins=["*", ],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
def start_cmd(cmd: list):
'''执行命令'''
response = subprocess.Popen(cmd, stdout=subprocess.PIPE, encoding='gb2312')
response1 = response.stdout.read()
return response1
def init_object():
'''初始化项目'''
run_time_file_set = ['.pyarmor.ikey',
'pyarmor_runtime_000000',
'pyarmor_runtime.pyd',
'__init__.py'] # 加密文件中应该存在的文件
now_file_set = [i.name for i in SHARED_RUNTIME.rglob('*')] # 实际存在的文件
diff = list(set(run_time_file_set) ^ set(now_file_set)) # 取差集
if diff:
logger.warning(f'系统中加密库不全或无加密共享库,重新创建【{SHARED_RUNTIME}】')
if SHARED_RUNTIME.exists():
shutil.rmtree(SHARED_RUNTIME)
cmd = [
f'{PYARMOR}',
f'gen',
f'runtime',
f'-O',
f'{SHARED_RUNTIME}'
]
start_cmd(cmd)
logger.success(f'共享加密库已创建成功~')
@app.post("/compile")
async def compile(file: UploadFile = File(...)):
'''加密文件'''
logger.warning(f'图片保存地址:【{CACHE_PY}】')
with open(str(CACHE_PY), 'wb') as f:
for i in iter(lambda: file.file.read(512), b''):
f.write(i)
start_cmd([
f'{PYARMOR}',
f'gen',
f'--use-runtime',
f'{SHARED_RUNTIME}',
f'-O',
f'{CACHE_PY.parent}',
f'{CACHE_PY}'
])
for item in tqdm.tqdm([1, 2, 3]):
time.sleep(0.3)
return FileResponse(
path=CACHE_PY,
filename=CACHE_PY.name, # 下载时显示的文件名(可选)
media_type='application/octet-stream',
)
if __name__ == '__main__':
init_object()
uvicorn.run(app, host='0.0.0.0', port=8001, workers=1)
客户端
from pathlib import Path
from loguru import logger
import requests
class Compile(object):
'''编译'''
def __init__(self):
self.url = 'http://43.138.47.118:8010/compile'
self._desk_top = Path.home().joinpath("Desktop")
def save_file(self, response, filename):
'''保存文件'''
file_abs_path = self._desk_top.joinpath(filename)
with open(file_abs_path, 'wb') as f:
f.write(response)
logger.success(f'编译成功:【{file_abs_path}】')
def start(self, file_path):
'''开始编译'''
logger.debug(f'开始云编译;【{file_path}】')
filename = Path(file_path).name
with open(file_path, 'rb') as f:
file = f.read()
response = requests.post(self.url, files={"file": (filename, file)}).content
self.save_file(response, filename)
if __name__ == '__main__':
a = Compile()
a.start(r'D:\code\ceshi\main.py')
更多推荐


所有评论(0)