-
Notifications
You must be signed in to change notification settings - Fork 647
/
Copy pathdownload_checkmd5.py
executable file
·69 lines (55 loc) · 1.9 KB
/
download_checkmd5.py
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
#!/usr/bin/env python2
import urllib, hashlib, sys, os
from optparse import OptionParser
class AppURLopener(urllib.FancyURLopener):
version ="Mozilla/5.0 (Macintosh; U; Intel Mac OS X; en-US; rv:1.8.0.7) Gecko/20060909 Firefox/1.5.0.7"
def prompt_user_passwd(self, host, realm):
raise Exception()
urllib._urlopener = AppURLopener()
def file_md5(file):
m = hashlib.md5()
m.update(open(dest).read())
return m.hexdigest()
def main():
parser = OptionParser(usage="usage: %prog URI dest [md5sum]", prog=sys.argv[0])
options, args = parser.parse_args()
md5sum = None
if len(args)==2:
uri, dest = args
elif len(args)==3:
uri, dest, md5 = args
else:
parser.error("Wrong arguments")
fresh = False
if not os.path.exists(dest):
print "Downloading from %s to %s..."%(uri, dest),
sys.stdout.flush()
urllib.urlretrieve(uri, dest)
print "done"
fresh = True
if md5sum:
print "Computing md5sum on downloaded file",
sys.stdout.flush()
checksum = md5_file(dest)
print "done"
if checksum!=md5sum:
if not fresh:
print "Checksum mismatch (%s != %s), re-downloading file %s"%(checksum, md5sum, dest),
sys.stdout.flush()
os.remove(dest)
urllib.urlretrieve(uri, dest)
print "done"
print "Computing md5sum on downloaded file",
sys.stdout.flush()
checksum = md5_file(dest)
print "done"
if checksum!=md5sum:
print "ERROR, checksum mismatch (%s != %s) on %d",(checksum, md5sum, dest)
return 1
return 0
if __name__ == '__main__':
try:
sys.exit(main())
except Exception as e:
print "ERROR, ",e
sys.exit(1)