Board logo

标题: [原创教程] python读取配置文件对比文件MD5.py [打印本页]

作者: codegay    时间: 2016-2-27 04:17     标题: python读取配置文件对比文件MD5.py

本帖最后由 codegay 于 2016-2-27 14:14 编辑
  1. """
  2. python读取配置文件对比文件MD5.py
  3. http://www.oschina.net/question/2635041_2151586
  4. 2016年2月26日 21:09:52 codegay
  5. """
  6. import re
  7. import hashlib
  8. def configmd5(file="file.md5"):
  9.     configdict={r.rstrip("\n").split(":")[0]:r.rstrip("\n").split(":")[1] for r in open(file).readlines()}
  10.     return configdict
  11. def configmd51(file="file.md5"):
  12.     configdict={}
  13.     for r in open(file):
  14.         fmd5=r.rstrip("\n").split(":")
  15.         configdict[fmd5[0]]=fmd5[1]
  16.     return configdict
  17. def reconfigmd5(file="file.md5"):
  18.     import re
  19.     txt=open(file).read()
  20.     result=re.findall(r"(.*/?.+):([a-fA-F0-9]{32})",txt)
  21.     configdict={k:v for k,v in result}
  22.     return configdict
  23. #以上三个函数功能一样,都是读取配置文件file.md5数据成对格式化为字典。
  24. def md5(seq):
  25.     results={}
  26.     for s in seq:
  27.         #如果考虑处理超大的文件或者控制内存的占用量,
  28.         #不能使用一次性读取文件的写法
  29.         fb=open(s,"rb").read()
  30.         fmd5=hashlib.md5(fb).hexdigest()
  31.         results[s]=[cmd5[s],fmd5,cmd5==fmd5]
  32.         #字典存储结果,{文件名作为键名:[配置文件中的MD5值,实际文件的MD5,对比结果]
  33.     print(results)
  34.     return results
  35.                
  36. cmd5=reconfigmd5()
  37. md5(cmd5.keys())
复制代码

作者: codegay    时间: 2016-2-27 06:07

  1. >>> import hashlib
  2. >>> hashlib.md5(open("c:/grep.exe","rb").read()).hexdigest()
  3. 'bb350a9ac2236b3e29f2229e77709f40'
复制代码

作者: codegay    时间: 2016-2-27 15:04

  1. import os
  2. import hashlib
  3. {r:hashlib.sha256(open(r,"rb").read()).hexdigest() for r in os.listdir() if os.path.isfile(r) and r.endswith(".exe")}
  4. #当前目录下所有.exe sha256的哈希值
复制代码





欢迎光临 批处理之家 (http://www.bathome.net/) Powered by Discuz! 7.2