-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathcloudstor
executable file
·113 lines (81 loc) · 2.68 KB
/
cloudstor
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#!/usr/bin/env python3
"""
Transfer files to Cloudstor
Uploading to Cloudstor requires an 'App Password', available from
https://cloudstor.aarnet.edu.au/plus/settings/personal?sectionid=security
Enter the username and password from the 'App Password' as '--user' and
'--token' respectively
"""
import subprocess
import argparse
import os
import xml.etree.ElementTree as ET
user = None
token = None
class DAVException(Exception):
pass
def curl_command(cmd, target):
r = subprocess.run(['curl', '-u', f'{user}:{token}', *cmd, f'https://cloudstor.aarnet.edu.au/plus/remote.php/webdav/{target}'], stdout=subprocess.PIPE)
r.check_returncode()
if len(r.stdout) == 0:
return None
root = ET.fromstring(r.stdout)
if root.tag == '{DAV:}error':
raise DAVException(root.find('{http://sabredav.org/ns}message').text, target)
return root
def put(path, target, recursive=False):
"""
Upload file at 'path' to 'target'
"""
if recursive:
put_recursive(path, target)
else:
if os.path.isdir(path):
raise Exception(f"Can't put directory {path} (try -r)")
print("PUT",path,target)
curl_command(['-T',path], target)
def mkdir(target):
"""
Make a directory 'target'
"""
print("MKDIR",target)
try:
curl_command(['-X','MKCOL'], target)
except DAVException as e:
if e.args[0] == 'The resource you tried to create already exists':
pass
else:
raise
def put_recursive(path, target):
"""
Upload the directory tree starting at 'path' to target
"""
mkdir(f"{target}")
for root, dirs, files in os.walk(path):
t = root[len(path):]
for d in dirs:
mkdir(f"{target}/{t}/{d}")
for f in files:
put(f"{root}/{f}",f"{target}/{t}/{f}")
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('--user','-u', required=True)
parser.add_argument('--token','-t', required=True)
subp = parser.add_subparsers(metavar="COMMAND")
sub_put = subp.add_parser('put', help="Upload files")
sub_put.add_argument("--recursive", "-r", action='store_true')
sub_put.add_argument("path")
sub_put.add_argument("target")
sub_put.set_defaults(func=put)
sub_mkdir = subp.add_parser('mkdir', help="Make directory")
sub_mkdir.add_argument("target")
sub_mkdir.set_defaults(func=mkdir)
args = parser.parse_args()
global user, token
args = vars(args)
user = args.pop('user')
token = args.pop('token')
func = args.pop('func')
func(**args)
if __name__ == '__main__':
main()