-
Notifications
You must be signed in to change notification settings - Fork 0
/
iftp.py
executable file
·274 lines (234 loc) · 9.24 KB
/
iftp.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
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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
#!/usr/bin/env python3
""" iCloud Drive ftp client
A command line ftp-styled client for iCloud Drive.
Needs latest pyicloud from https://github.com/ixs/pyicloud until PR is merged.
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation, either version 3 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
this program. If not, see <http://www.gnu.org/licenses/>.
"""
import cmd
import click
import datetime
import logging
import netrc
import os
import os.path
import time
import shlex
from pprint import pprint
from pyicloud import PyiCloudService
from shutil import copyfileobj
class Iftp(cmd.Cmd):
def __init__(self):
cmd.Cmd.__init__(self)
self._sort = True
self.prompt = "iftp> "
self._api = None
self._netrc = netrc.netrc()
self.path = []
self.user_path = "/"
def do_login(self, args):
"""Login into iCloud"""
try:
self.username, _, self.password = self._netrc.authenticators("icloud")
except TypeError:
self.username = click.prompt("iCloud Username")
self.password = click.prompt("iCloud Password")
self._login()
def do_ls(self, args):
"""List files"""
if not self.check_login():
print("Not logged in, login first")
return
if args == '':
args = self.user_path
else:
args = os.path.normpath(os.path.join(self.user_path, args))
path = self._get_handle_for_path(args)
if path:
for item in path.dir():
drive_file = path[item]
if drive_file.type == "file":
perms = "-rw-rw-rw-"
size = drive_file.size
date = drive_file.date_modified
if date.year == datetime.datetime.now().year:
filedate = date.strftime("%b %d %H:%S")
else:
filedate = date.strftime("%b %d %Y")
elif drive_file.type == "folder":
perms = "drwxrwxrwx"
size = 0
filedate = "Jan 01 1970"
print(
"%s %-4s %5s %-5s %13s %s %s"
% (perms, 0, os.getuid(), os.getgid(), size, filedate, drive_file.name)
)
return
def do_get(self, args):
"""Download file"""
if not self.check_login():
print("Not logged in, login first")
return
args = os.path.normpath(os.path.join(self.user_path, args))
drive_handle = self._get_handle_for_path(args)
if drive_handle and drive_handle.type == 'file':
starttime = time.time()
with drive_handle.open(stream=True) as response:
with open(drive_handle.name, "wb") as file_out:
copyfileobj(response.raw, file_out)
stoptime = time.time()
duration = stoptime - starttime
print("%s bytes received in %f secs (%f Kbytes/sec)" % (drive_handle.size, duration, drive_handle.size / duration / 1024))
else:
print("550 Failed to open file.")
return
def do_put(self, args):
"""Download file"""
if not self.check_login():
print("Not logged in, login first")
return
args = shlex.split(args)
if len(args) == 1:
sfile = args[0]
dfile = os.path.basename(sfile)
else:
(sfile, dfile) = args
head, tail = os.path.split(dfile)
if head:
drive_handle = self._get_handle_for_path(os.path.normpath(os.path.join(self.user_path, head)))
else:
drive_handle = self._get_handle_for_path(self.user_path)
if drive_handle and drive_handle.type == 'folder':
size = os.path.getsize(sfile)
starttime = time.time()
with open(sfile, 'rb') as file_in:
drive_handle.upload(file_in)
stoptime = time.time()
duration = stoptime - starttime
print("%s bytes sent in %f secs (%f Kbytes/sec)" % (size, duration, size / duration / 1024))
return
def do_mkdir(self, args):
"""Create new directory"""
if not self.check_login():
print("Not logged in, login first")
return
head, tail = os.path.split(args)
if head:
drive_handle = self._get_handle_for_path(os.path.normpath(os.path.join(self.user_path, head)))
else:
drive_handle = self._get_handle_for_path(self.user_path)
if drive_handle and drive_handle.type == 'folder':
drive_handle.mkdir(tail)
print('257 "%s" created' % os.path.normpath(os.path.join(self.user_path, head, tail)))
def do_rmdir(self, args):
"""Delete a directory"""
if not self.check_login():
print("Not logged in, login first")
return
args = os.path.normpath(os.path.join(self.user_path, args))
drive_handle = self._get_handle_for_path(args)
if drive_handle and drive_handle.type == 'folder':
drive_handle.delete()
print("250 Remove directory operation successful.")
else:
print("550 Remove directory operation failed.")
def do_delete(self, args):
"""Delete a file"""
if not self.check_login():
print("Not logged in, login first")
return
args = os.path.normpath(os.path.join(self.user_path, args))
drive_handle = self._get_handle_for_path(args)
if drive_handle and drive_handle.type == 'file':
drive_handle.delete()
print("250 Delete operation successful.")
else:
print("550 Delete operation failed.")
def do_rename(self, args):
"""Rename a file or folder"""
if not self.check_login():
print("Not logged in, login first")
return
sfile, dfile = shlex.split(args)
args = os.path.normpath(os.path.join(self.user_path, sfile))
drive_handle = self._get_handle_for_path(args)
drive_handle.rename(os.path.basename(dfile))
print("250 Rename successful.")
def do_pwd(self, args):
"""Show current directory"""
if not self.check_login():
print("Not logged in, login first")
return
print('%s "%s"' % (257, self.user_path))
def do_cd(self, args):
"""Change directory"""
if not self.check_login():
print("Not logged in, login first")
return
path = os.path.normpath(os.path.join(self.user_path, args))
drive_handle = self._get_handle_for_path(path)
if drive_handle and drive_handle.type == "folder":
print('%s "%s"' % (250, "Directory successfully changed."))
self.user_path = path
else:
print("%s %s" % (550, "Failed to change directory."))
return
def do_quit(self, args):
return -1
def do_EOF(self, args):
return -1
def check_login(self):
if self._api is None:
return False
return True
def _login(self):
self._api = PyiCloudService(self.username, self.password)
if self._api.requires_2sa:
print("Two-factor authentication required. Your trusted devices are:")
devices = self._api.trusted_devices
for i, device in enumerate(devices):
print(
" %s: %s"
% (
i,
device.get("deviceName", "SMS to %s")
% device.get("phoneNumber"),
)
)
device = click.prompt("Which device would you like to use?", default=0)
device = devices[device]
if not self._api.send_verification_code(device):
print("Failed to send verification code")
sys.exit(1)
code = click.prompt("Please enter validation code")
if not self._api.validate_verification_code(device, code):
print("Failed to verify verification code")
sys.exit(1)
print("Logged into iCloud Drive as %s" % self.username)
def _verify_path(self, path):
pass
def _get_handle_for_path(self, args):
"""Get a drive API handle for a path"""
drive_handle = self._api.drive
# Handle '/' and just return the base drive_handle
if args.strip() == '/':
return drive_handle
tmppath = args.split("/")
# Cut leading /
if tmppath[0] == "" and len(tmppath) > 1:
tmppath.pop(0)
try:
for element in tmppath:
drive_handle = drive_handle[element]
return drive_handle
except KeyError:
return False
if __name__ == "__main__":
Iftp().cmdloop()