-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcheck_file_md5.py
More file actions
72 lines (60 loc) · 1.85 KB
/
check_file_md5.py
File metadata and controls
72 lines (60 loc) · 1.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# coding: utf-8
'''
用于检查文件md5是否正确,类似linux下md5sum -c md5.txt的功能
'''
import sys
import os
import getopt
import hashlib
def get_md5(argv):
for filename in argv:
if os.path.isfile(filename):
fb = open(filename,'rb')
md5 = hashlib.md5(fb.read()).hexdigest()
fb.close()
print(md5 + ' ' + filename)
else:
print('< ' + filename + ' > No such file.')
def check_md5(md5file):
if os.path.isfile(md5file):
pass
else:
print('md5file not found.')
sys.exit(1)
for line in open(md5file, 'r').readlines():
if len(line.split()) == 2:
filemd5 = line.split()[0]
filename = line.split()[1]
# print(line.strip())
if os.path.isfile(filename):
fb = open(filename,'rb')
md5 = hashlib.md5(fb.read()).hexdigest()
fb.close()
if filemd5 == md5:
print(filename + ': OK')
else:
print(filename + ': FAILED')
else:
print(filename + ' not found.')
else:
print(line.strip() + ' data error')
def main(argv):
try:
opts, args = getopt.getopt(argv, "hc:", ["help", "check="])
#print(opts)
#print(args)
except getopt.GetoptError:
print(sys.argv[0] + ' -c/--check <md5_filename>')
sys.exit(2)
if len(args) == 0:
for opt, arg in opts:
if opt in ("-h", "--help", "help"):
print(sys.argv[0] + ' -c/--check <md5_filename>')
sys.exit()
elif opt in ("-c", "--check"):
md5file = arg
check_md5(md5file)
else:
get_md5(args)
if __name__ == "__main__":
main(sys.argv[1:])