使用文件捕捉器和加密技术,可以实现对 Python 文件的保护。以下是示例代码:
import os
import hashlib
def protect_file(filename):
# 计算文件的 MD5 值
content = ''
with open(filename, 'rb') as f:
content = f.read()
md5 = hashlib.md5(content).hexdigest()
# 在文件名中添加 MD5 值
new_filename = f'{filename}_{md5}'
os.rename(filename, new_filename)
def check_file():
# 检查文件是否被更改
content = ''
with open(new_filename, 'rb') as f:
content = f.read()
current_md5 = hashlib.md5(content).hexdigest()
if current_md5 != md5:
print('文件已被更改!')
os.rename(new_filename, filename)
return check_file
上面的代码定义了一个 protect_file
函数,它将文件名作为参数,并返回一个 check_file
函数。protect_file
函数会在文件名中添加 MD5 值,并将文件重命名为新的文件名。check_file
函数可以用于检查文件是否被更改过。如果文件被更改了,它会输出一条警告,并将文件重命名为原始文件名(即去掉 MD5 值的文件名)。例如:
my_file.py = "print('Hello, world!')"
check_file = protect_file('my_file.py')
check_file() # 运行正常,输出:None
# 修改 my_file.py,将其中的 "Hello, world!" 改为 "Goodbye, world!"
my_file.py = "print('Goodbye, world!')"
check_file() # 运行结果:文件已被更改!
下一篇:保护Python应用程序