| 1 |
#!/usr/bin/env python3 |
| 2 |
""" |
| 3 |
Small script to upload file using HTTP PUT |
| 4 |
""" |
| 5 |
|
| 6 |
import argparse |
| 7 |
import os |
| 8 |
import sys |
| 9 |
|
| 10 |
import requests |
| 11 |
|
| 12 |
|
| 13 |
def main(): |
| 14 |
parser = argparse.ArgumentParser( |
| 15 |
description='Upload a file using HTTP PUT method', |
| 16 |
epilog=( |
| 17 |
"To use HTTP Auth set HTTP_PUT_AUTH environment variable to user:password\n" |
| 18 |
"Example: %(prog)s file1 file2 https://example.com/dir/")) |
| 19 |
parser.add_argument( |
| 20 |
"file", type=argparse.FileType('rb'), nargs='+', help="File to upload") |
| 21 |
parser.add_argument( |
| 22 |
"dir_url", help="Remote URL (path to a directory, must include a trailing /)") |
| 23 |
args = parser.parse_args() |
| 24 |
|
| 25 |
if not args.dir_url.endswith('/'): |
| 26 |
parser.error("URL must end with /") |
| 27 |
|
| 28 |
http_auth = os.getenv('HTTP_PUT_AUTH') |
| 29 |
if http_auth: |
| 30 |
user, password = http_auth.split(':') |
| 31 |
auth = (user, password) |
| 32 |
else: |
| 33 |
auth = None |
| 34 |
|
| 35 |
exit_code = 0 |
| 36 |
|
| 37 |
for fh in args.file: |
| 38 |
try: |
| 39 |
r = requests.put(args.dir_url + fh.name, data=fh, auth=auth, timeout=(45, 90)) |
| 40 |
r.raise_for_status() |
| 41 |
print("{} uploaded to {}".format(fh.name, r.url)) |
| 42 |
except (requests.exceptions.ConnectionError, |
| 43 |
requests.exceptions.HTTPError) as err: |
| 44 |
print(err, file=sys.stderr) |
| 45 |
exit_code = 1 |
| 46 |
|
| 47 |
return exit_code |
| 48 |
|
| 49 |
|
| 50 |
if __name__ == '__main__': |
| 51 |
sys.exit(main()) |