py脚本加密

编译成pyc

要强调的是,编译pyc和运行pyc的python环境必须一致,不然无法运行。

pyc的运行方式和相互import方式和py脚本完全一样。

对于一个完整项目进行pyc加密的脚本:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import compileall
import sys
import os
import shutil

try:
path = sys.argv[1]
except:
path = '/home/muzhen/database/repositories/ae-server-confusion'
print(path)

def confusion(path):
for root,dirs,files in os.walk(path):
if os.path.basename(root) == '__pycache__':
shutil.rmtree(root)
for root,dirs,files in os.walk(path):
for file in files:
if file.rsplit('.',1)[-1] == 'pyc':
os.remove(os.path.join(root,file))

compileall.compile_dir(path)

for root,dirs,files in os.walk(path):
for file in files:
if file.rsplit('.',1)[-1] == 'pyc':
print(file)
src = os.path.join(root,file)
file_n = file.rsplit('.',2)[0] + '.pyc'
file_n_del = file.rsplit('.',2)[0] + '.py'
dst = os.path.join(os.path.dirname(root),file_n)
dst_del = os.path.join(os.path.dirname(root),file_n_del)
shutil.copy(src,dst)
os.remove(dst_del)
for root,dirs,files in os.walk(path):
if os.path.basename(root) == '__pycache__':
shutil.rmtree(root)

confusion(path)

references

python下编译py成pyc和pyo