今天是又一年度的2月14日西方情人节,先说点与情人节有关的,但这绝不是狗粮,可以放心阅读。讲真,如果你是单身狗,没事时还是要静下心学习以提升自己;如果你不是单身狗,没事时除了上一条还要多陪陪媳妇和家人。因为没有什么是比亲人和提升自己更重要的事了!无论是提升自己还是陪伴家人,不要浮于表面,就像今天过情人节一样,向对方表达爱并不是只有这一天和那几天,而是男女双方长久的坚持和包容。
用以前有人用过的句子说:当你的才华撑不起你的野心,那你就应该静下心来学习;当你的金钱赶不上你的梦想,那你就应该坐下来好好工作;当你的能力还驾驭不了你的目标,那就应该沉下心来历练!
正文开始:
本文为使用Python脚本检验文件系统数据完整性和防止数据篡改提供一种简单且容易实现的思路(其实很简单,只需要了解Python基础+hashlib+文件操作等)。
虽然校验数据完整性这个话题已经由很多更加完美的解决办法,但依然可以作为Python新手练手内容之一,培养一下逻辑思维,防止“老年痴呆”。
目前已经在Windows 10以及Ubuntu(Python 2.7)下测试通过,其他的平台应该也可以,欢迎帮忙测试。
编写的思路和执行过程简要如下:
1.输入要检查数据完整性的目录的路径(也支持单个文件)和要保存文件hash值的校验文件的路径,如果路径不存在,则抛出异常或者创建,取决于具体情况;
参数传入(最新版本将参数传入通过命令行的方式传入了,下面图片中是老版本中的参数传入):
在刚更新的版本中,参数传入和命令帮助通过docopt模块实现,方便使用。Python script to check data integrity on UNIX/Linux or Windows
accept options using 'docopt' module, using 'docopt' to accept parameters and command switch
Usage:
checkDataIntegrity.py [-g FILE HASH_FILE]
checkDataIntegrity.py [-c FILE HASH_FILE]
checkDataIntegrity.py [-r HASH_FILE]
checkDataIntegrity.py generate FILE HASH_FILE
checkDataIntegrity.py validate FILE HASH_FILE
checkDataIntegrity.py reset HASH_FILE
checkDataIntegrity.py (--version | -v)
checkDataIntegrity.py --help | -h | -?
Arguments:
FILE the path to single file or directory to data protect
HASH_FILE the path to hash data saved
Options:
-? -h --help show this help message and exit
-v --version show version and exit
Example, try:
checkDataIntegrity.py generate /tmp /tmp/data.json
checkDataIntegrity.py validate /tmp /tmp/data.json
checkDataIntegrity.py reset /tmp/data.json
checkDataIntegrity.py -g /tmp /tmp/data.json
checkDataIntegrity.py -c /tmp /tmp/data.json
checkDataIntegrity.py -r /tmp/data.json
checkDataIntegrity.py --help
合法的参数和路径:
路径不存在时抛出异常: