-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathclient.py
503 lines (393 loc) · 14.5 KB
/
client.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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
import socket
import errno
class FtpClient(object):
"""
This class offers a simple interface to interact with an FTP server.
Attributes:
host (str): The host to which the client is connected to, if connected,
None otherwise.
user (str): The username of the logged in user, if logged in, None
otherwise.
"""
class ConnectionRefusedException(socket.error):
"""
Exception raised when an FTP host refuses a connection.
Args:
host (str): Host that refused connection.
Attributes:
msg (str): Human readable string describing the exception.
"""
def __init__(self, host):
super(FtpClient.ConnectionRefusedException, self).__init__()
self.msg = 'Connection to {}:{} failed. Connection refused.'\
.format(host, FtpClient.PORT)
class UnknownHostException(socket.gaierror):
"""
Exception raised when an FTP host is unreachable.
Args:
host (str): Unreachable host.
Attributes:
msg (str): Human readable string describing the exception.
"""
def __init__(self, host):
super(FtpClient.UnknownHostException, self).__init__()
self.msg = 'Connection to {}:{} failed. Host not reachable.'\
.format(host, FtpClient.PORT)
class TimeoutException(socket.timeout):
"""
Exception raised when the FTP client socket connection has timed out.
Args:
host (str): Host for which the connection timed out.
Attributes:
msg (str): Human readable string describing the exception.
"""
def __init__(self, host):
super(FtpClient.TimeoutException, self).__init__()
self.msg = 'Connection to {}:{} timed out'.format(host,
FtpClient.PORT)
class NotConnectedException(Exception):
"""
Exception raised when FTP commands are performed but the client
is not currently connected to a host.
Attributes:
msg (str): Human readable string describing the exception.
"""
def __init__(self):
super(FtpClient.NotConnectedException, self).__init__()
self.msg = 'Not connected.'
class NotAuthenticatedException(Exception):
"""
Exception raised when FTP commands are performed but the client
is not currently authenticated for a user in the host.
Attributes:
msg (str): Human readable string describing the exception.
"""
def __init__(self):
super(FtpClient.NotAuthenticatedException, self).__init__()
self.msg = 'Not authenticated.'
class LocalIOException(IOError):
"""
Exception raised when something goes wrong during local IO operations.
Attributes:
msg (str): Human readable string describing the exception.
"""
def __init__(self, msg):
super(FtpClient.LocalIOException, self).__init__()
self.msg = 'Local IO error - {}'.format(msg)
PORT = 21
SOCKET_TIMEOUT_SECONDS = 5
SOCKET_RCV_BYTES = 4096
LIST_COMMAND = 'LIST'
USER_COMMAND = 'USER'
PASS_COMMAND = 'PASS'
EPRT_COMMAND = 'EPRT'
QUIT_COMMAND = 'QUIT'
RETR_COMMAND = 'RETR'
STOR_COMMAND = 'STOR'
PWD_COMMAND = 'PWD'
CWD_COMMAND = 'CWD'
CDUP_COMMAND = 'CDUP'
MKD_COMMAND = 'MKD'
DELE_COMMAND = 'DELE'
RMD_COMMAND = 'RMD'
RNFR_COMMAND = 'RNFR'
RNTO_COMMAND = 'RNTO'
STATUS_230 = '230'
STATUS_550 = '550'
STATUS_530 = '530'
def __init__(self, debug=False):
self._debug = debug
self._reset_sockets()
def _log(self, info):
if self._debug:
print('debug: {}'.format(info))
def _reset_sockets(self):
self._reset_command_socket()
self._reset_data_socket()
self.host = None
self.user = None
def _reset_command_socket(self):
if getattr(self, 'host', None) is not None:
self._command_socket.close()
self._command_socket = socket.socket()
self._command_socket.settimeout(FtpClient.SOCKET_TIMEOUT_SECONDS)
def _reset_data_socket(self):
if getattr(self, '_data_socket_listening', False):
self._data_socket.close()
self._data_socket = socket.socket()
self._data_socket_listening = False
def _send_command(self, command, *args):
for a in args:
command = '{} {}'.format(command, a)
try:
self._log('sending command - {}'.format(command))
self._command_socket.sendall('{}\r\n'.format(command))
except socket.timeout:
raise FtpClient.TimeoutException(self.host)
def _receive_command_data(self):
data = self._command_socket.recv(FtpClient.SOCKET_RCV_BYTES)
self._log('received command data - {}'.format(data))
return data
def _check_is_connected(self):
if self.host is None:
raise FtpClient.NotConnectedException()
def _check_is_authenticated(self):
if self.user is None:
raise FtpClient.NotAuthenticatedException()
def _open_data_socket(self):
self._data_address, self._data_port = \
self._command_socket.getsockname()
self._data_port = self._data_port + 1
self._data_socket.bind(('', self._data_port))
self._data_socket.listen(1)
self._data_socket_listening = True
def _open_data_connection(self):
if not self._data_socket_listening:
self._open_data_socket()
self._send_command(FtpClient.EPRT_COMMAND, '|1|{}|{}|'
.format(self._data_address, self._data_port))
self._data_connection, address = self._data_socket.accept()
self._log('opened data connection on {}'.format(address))
data = self._receive_command_data()
return data
def _read_from_data_connection(self):
total_data = ''
while True:
data = self._data_connection.recv(FtpClient.SOCKET_RCV_BYTES)
total_data = total_data + data
if not data:
break
self._data_connection.close()
self._log('received data - {}'.format(total_data))
return total_data
def _write_to_data_connection(self, content):
self._log('sending data - {}'.format(content))
self._data_connection.sendall(content)
self._data_connection.close()
def connect(self, host=None):
"""
Connect to an FTP server in the specified host.
Args:
host (str): The host to connect to. Falsy values
default to `localhost`. (Optional)
Returns:
Message from host.
"""
host = host or 'localhost'
if self.host is not None:
self._reset_sockets()
try:
self._log('connecting to {}:{}'.format(host, FtpClient.PORT))
self._command_socket.connect((host, FtpClient.PORT))
self.host = host
except socket.timeout:
self._reset_sockets()
raise FtpClient.TimeoutException(host)
except socket.gaierror:
self._reset_sockets()
raise FtpClient.UnknownHostException(host)
except socket.error as e:
if e.errno == errno.ECONNREFUSED:
raise FtpClient.ConnectionRefusedException(host)
return self._receive_command_data()
def login(self, user, password):
"""
Login with specified user and password on the connected host.
Args:
user (str): The user.
password (str): The password.
Returns:
Message from host.
"""
self._check_is_connected()
self._send_command(FtpClient.USER_COMMAND, user)
self._receive_command_data()
self._send_command(FtpClient.PASS_COMMAND, password)
data = self._receive_command_data()
if data.startswith(FtpClient.STATUS_230):
self.user = user
elif data.startswith(FtpClient.STATUS_530):
self.user = None
return data
def logout(self):
"""
Clear info about currently logged user on connected host.
"""
self._check_is_connected()
self._check_is_authenticated()
self._log('logging out {}'.format(self.user))
self.user = None
def list(self, filename=None):
"""
Perform LIST command on connected host.
Args:
filename (str): Name of file or directory to retrieve info
for. (Optional)
Returns:
Message and data from host.
"""
self._check_is_connected()
self._check_is_authenticated()
data = self._open_data_connection()
if filename is not None:
self._send_command(FtpClient.LIST_COMMAND, filename)
else:
self._send_command(FtpClient.LIST_COMMAND)
list_data = self._receive_command_data()
data = data + list_data
if not list_data.startswith(FtpClient.STATUS_550):
data = data + self._read_from_data_connection()
data = data + self._receive_command_data()
return data
def disconnect(self):
"""
Perform QUIT command (disconnect) on connected host.
Returns:
Message from host.
"""
self._check_is_connected()
self._send_command(FtpClient.QUIT_COMMAND)
data = self._receive_command_data()
self._reset_sockets()
return data
def retrieve(self, filename, local_filename):
"""
Perform RETR command on connected host.
Args:
filename (str): Name of file to retrieve.
local_filename (str): Name of local file to create.
Returns:
If successful, the tuple containing the message from the host,
and the file descriptor for the new file.
"""
self._check_is_connected()
self._check_is_authenticated()
data = self._open_data_connection()
self._send_command(FtpClient.RETR_COMMAND, filename)
retr_data = self._receive_command_data()
data = data + retr_data
local_file = None
if not retr_data.startswith(FtpClient.STATUS_550):
content = self._read_from_data_connection()
try:
local_file = open(local_filename, 'w+')
local_file.write(content)
local_file.close()
except IOError as e:
raise FtpClient.LocalIOException(e.strerror)
data = data + self._receive_command_data()
return data, local_file
def store(self, local_filename, filename):
"""
Perform STOR command on connected host.
Args:
local_filename (str): Name of local file to send.
filename (str): Name of remote file to create.
Returns:
Message from host.
"""
self._check_is_connected()
self._check_is_authenticated()
data = self._open_data_connection()
try:
local_file = open(local_filename, 'r')
self._send_command(FtpClient.STOR_COMMAND, filename)
data = data + self._receive_command_data()
self._write_to_data_connection(local_file.read())
local_file.close()
except IOError as e:
raise FtpClient.LocalIOException(e.strerror)
data = data + self._receive_command_data()
return data
def pwd(self):
"""
Perform PWD command on connected host.
Returns:
Message from host.
"""
self._check_is_connected()
self._check_is_authenticated()
self._send_command(FtpClient.PWD_COMMAND)
data = self._receive_command_data()
return data
def cwd(self, directory):
"""
Perform CWD command on connected host.
Args:
directory (str): Name of directory to work on.
Returns:
Message from host.
"""
self._check_is_connected()
self._check_is_authenticated()
self._send_command(FtpClient.CWD_COMMAND, directory)
data = self._receive_command_data()
return data
def cdup(self):
"""
Perform CDUP command on connected host.
Returns:
Message from host.
"""
self._check_is_connected()
self._check_is_authenticated()
self._send_command(FtpClient.CDUP_COMMAND)
data = self._receive_command_data()
return data
def mkdir(self, directory):
"""
Perform MKD command on connected host.
Args:
directory (str): Name of directory to create.
Returns:
Message from host.
"""
self._check_is_connected()
self._check_is_authenticated()
self._send_command(FtpClient.MKD_COMMAND, directory)
data = self._receive_command_data()
return data
def rm(self, filename):
"""
Perform DELE command on connected host.
Args:
filename (str): Name of file to delete.
Returns:
Message from host.
"""
self._check_is_connected()
self._check_is_authenticated()
self._send_command(FtpClient.DELE_COMMAND, filename)
data = self._receive_command_data()
return data
def rmdir(self, directory):
"""
Perform RMD command on connected host.
Args:
directory (str): Name of directory to delete.
Returns:
Message from host.
"""
self._check_is_connected()
self._check_is_authenticated()
self._send_command(FtpClient.RMD_COMMAND, directory)
data = self._receive_command_data()
return data
def rename(self, from_name, to_name):
"""
Perform RNFR + RNTO (rename file or directory) command on connected
host.
Args:
from_name (str): Original name of file or directory.
to_name (str): New name for file or directory.
Returns:
Message from host.
"""
self._check_is_connected()
self._check_is_authenticated()
self._send_command(FtpClient.RNFR_COMMAND, from_name)
data = self._receive_command_data()
if not data.startswith(FtpClient.STATUS_550):
self._send_command(FtpClient.RNTO_COMMAND, to_name)
data = data + self._receive_command_data()
return data