~fincham/static-binary-zoo

ref: e79e3898beb4586fb1a60be3f747649c0b38029e static-binary-zoo/download -rwxr-xr-x 1.4 KiB
e79e3898 — Michael Fincham Spelling 5 months ago
                                                                                
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
#!/usr/bin/python3 -u

"""
Download a file from a URL and validate the SHA256 checksum while downloading.

Michael Fincham <michael@hotplate.co.nz> 2021-08-20
"""

import sys
import os
import argparse
import hashlib
import urllib.request
import tempfile

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        "url", help="URL to download from"
    )
    parser.add_argument(
        "destination",
        help="destination file"
    )
    parser.add_argument(
        "sha256sum",
        help="SHA256 checksum to match again"
    )
    args = parser.parse_args()

    block_size = 1024 * 1024
    checksum = hashlib.sha256()
    response = urllib.request.urlopen(args.url)
    return_code = 0
    sha256sum = args.sha256sum.lower()
    print("Downloading '%s'..." % args.url)
    with tempfile.NamedTemporaryFile() as f:
        while True:
            block = response.read(block_size)
            if not block:
                break
            f.write(block)
            checksum.update(block)
            print(".", end="")
        print("")
        if checksum.hexdigest() == sha256sum:
            os.link(f.name, args.destination)
        else:
            sys.stderr.write("error: checksum didn't match for '%s', not saving file. got %s and expected %s.\n" % (args.url, checksum.hexdigest(), sha256sum))
            return_code = 1
    sys.exit(return_code)