python - 如何检查脚本是否未被修改 - 尝试使用 git 属性 ident $Id$
问题描述
我正在维护一组分布在多台计算机上的 python 脚本。用户可能有修改脚本的奇思妙想,所以我正在寻找一种自动解决方案来检查脚本的完整性。
我想使用 git 属性ident
,以便文件包含自己的sha1
,然后用于git hash-object
比较。
它看起来像这样(.gitattributes 包含*.py ident
):
import subprocess
gitId= '$Id: 98a648abdf1cd8d563c72886a601857c20670013 $' #this sha will be updated automatically at each commit on the file.
gitId=gitId[5:-2]
shaCheck=subprocess.check_output(['git', 'hash-object', __file__]).strip().decode('UTF-8')
if shaCheck != gitId:
print('file has been corrupted \n {} <> {}'.format(shaCheck, gitId))
# below the actual purpose of the script
当我的脚本位于 git 存储库内但在git hash-object
我的 git 存储库之外返回不同的 sha 时,这工作正常。我想有一些 git 过滤器问题,但我不知道如何解决这个问题?
也欢迎任何其他轻松检查我的文件完整性的方法。
解决方案
您可以使用 Python 模块hashlib检查文件的哈希:
import hashlib
filename_1 = "./folder1/test_script.py"
with open(filename_1,"rb") as f:
bytes = f.read() # read entire file as bytes
readable_hash = hashlib.sha256(bytes).hexdigest();
print(readable_hash)
filename_2 = "./folder2/test_script.py"
with open(filename_2,"rb") as f:
bytes = f.read() # read entire file as bytes
readable_hash = hashlib.sha256(bytes).hexdigest();
print(readable_hash)
输出:
a0c22dc5d16db10ca0e3d99859ffccb2b4d536b21d6788cfbe2d2cfac60e8117 a0c22dc5d16db10ca0e3d99859ffccb2b4d536b21d6788cfbe2d2cfac60e8117
推荐阅读
- python - 列数不一致
- javascript - Grunt Spawn 任务并获得结果
- intellij-idea - 一般如何修复“URI目标不存在”?
- javascript - 在 div 中打开底页
- jquery - Ajax post 功能在 laravel 文档中不起作用
- javascript - 为什么我的窗口滚动事件会导致滚动中断?
- sql - Google Big Query 中的数据透视表
- auth0 - Auth0 使用通用登录的静默身份验证
- mysql - 如何从 MySQL 中与服务器不同时区的日期字段中选择 unix 时间戳?
- java - 尝试使用 web3j 部署以太坊智能合约时出错