首页 > 解决方案 > 如何检查脚本是否未被修改 - 尝试使用 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 过滤器问题,但我不知道如何解决这个问题?

也欢迎任何其他轻松检查我的文件完整性的方法。

标签: pythongitsha1

解决方案


您可以使用 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


推荐阅读