forked from kowalpy/Robot-Framework-FTP-Library
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFtpLibrary.py
More file actions
531 lines (483 loc) · 19.6 KB
/
FtpLibrary.py
File metadata and controls
531 lines (483 loc) · 19.6 KB
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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
#Robot Framework FTP Library
#
#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
#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/>.
#to generate libdoc documentation run:
# python -m robot.libdoc FtpLibrary FtpLibrary.html
import ftplib
import os
import socket
from robot.api import logger
class FtpLibrary(object):
"""
This library provides functionality of FTP client.
Version 1.8 released on 30th of December 2019
What's new in release 1.8:
- TLS support by Antonpaa
- one bugfix by Jarkko Peltonen
FTP communication provided by ftplib.py
Author: [https://github.com/kowalpy|Marcin Kowalczyk]
Website: https://github.com/kowalpy/Robot-Framework-FTP-Library
Installation:
- run command: pip install robotframework-ftplibrary
OR
- download, unzip and run command: python setup.py install
The simplest example (connect, change working dir, print working dir, close):
| ftp connect | 192.168.1.10 | mylogin | mypassword |
| cwd | /home/myname/tmp/testdir |
| pwd |
| ftp close |
It is possible to use multiple ftp connections in parallel. Connections are
identified by string identifiers:
| ftp connect | 192.168.1.10 | mylogin | mypassword | connId=ftp1 |
| ftp connect | 192.168.1.20 | mylogin2 | mypassword2 | connId=ftp2 |
| cwd | /home/myname/tmp/testdir | ftp1 |
| cwd | /home/myname/tmp/testdir | ftp2 |
| pwd | ftp2 |
| pwd | ftp1 |
| ftp close | ftp2 |
| ftp close | ftp1 |
To run library remotely execute: python FtpLibrary.py <ipaddress> <portnumber>
(for example: python FtpLibrary.py 192.168.0.101 8222)
"""
ROBOT_LIBRARY_SCOPE = 'TEST SUITE'
def __init__(self, printOutput=True):
"""
During library import it is possible to disable logging of server messages.
By default logging is enabled:
| Library | FtpLibrary.py |
To disable logging of server messages, additional parameter must be added to
import:
| Library | FtpLibrary.py | False |
"""
self.ftpList = {}
if isinstance(printOutput, bool):
self.printOutput = printOutput
else:
if printOutput == "False":
self.printOutput = False
else:
self.printOutput = True
def __getConnection(self, connId):
if connId in self.ftpList:
return self.ftpList[connId]
else:
errMsg = "Connection with ID %s does not exist. It should be created before this step." % connId
raise FtpLibraryError(errMsg)
def __addNewConnection(self, connObj, connId):
if connId in self.ftpList:
errMsg = "Connection with ID %s already exist. It should be deleted before this step." % connId
raise FtpLibraryError(errMsg)
else:
self.ftpList[connId] = connObj
def __removeConnection(self, connId):
if connId in self.ftpList:
self.ftpList.pop(connId)
def __isTlsConnection(self, connObject):
if not isinstance(connObject, ftplib.FTP_TLS):
raise FtpLibraryError("Keyword should be used only with TLS connection")
def __isRegularConnection(self, connObject):
if not isinstance(connObject, ftplib.FTP):
raise FtpLibraryError("Non regular connection")
def getAllFtpConnections(self):
"""
Returns a dictionary containing active ftp connections.
"""
outputMsg = "Current ftp connections:\n"
counter = 1
for k in self.ftpList:
outputMsg += str(counter) + ". " + k + " "
outputMsg += str(self.ftpList[k]) + "\n"
counter += 1
if self.printOutput:
logger.info(outputMsg)
return self.ftpList
def ftp_connect(self, host, user='anonymous', password='anonymous@', port=21, timeout=30, connId='default', tls=False, mode='passive'):
"""
Constructs FTP object, opens a connection and login. TLS support is optional.
Call this function before any other (otherwise raises exception).
Returns server output.
Parameters:
- host - server host address
- user(optional) - FTP user name. If not given, 'anonymous' is used.
- password(optional) - FTP password. If not given, 'anonymous@' is used.
- port(optional) - TCP port. By default 21.
- timeout(optional) - timeout in seconds. By default 30.
- connId(optional) - connection identifier. By default equals 'default'
- tls(optional) - TLS connections flag. By default False
- mode(optional) - set the transfer mode to 'active' or 'passive'. By default 'passive'
Examples:
| ftp connect | 192.168.1.10 | mylogin | mypassword | | |
| ftp connect | 192.168.1.10 | | | | |
| ftp connect | 192.168.1.10 | mylogin | mypassword | connId=secondConn | |
| ftp connect | 192.168.1.10 | mylogin | mypassword | 29 | 20 |
| ftp connect | 192.168.1.10 | mylogin | mypassword | 29 | |
| ftp connect | 192.168.1.10 | mylogin | mypassword | timeout=20 | |
| ftp connect | 192.168.1.10 | port=29 | timeout=20 | | |
| ftp connect | 192.168.1.10 | port=29 | timeout=20 | mode=active | |
"""
if connId in self.ftpList:
errMsg = "Connection with ID %s already exist. It should be deleted before this step." % connId
raise FtpLibraryError(errMsg)
else:
newFtp = None
outputMsg = ""
try:
timeout = int(timeout)
port = int(port)
newFtp = None
if tls:
newFtp = ftplib.FTP_TLS()
else:
newFtp = ftplib.FTP()
outputMsg += newFtp.connect(host, port, timeout)
self.__addNewConnection(newFtp, connId)
outputMsg += newFtp.login(user, password)
# set mode depending of "mode" value. if it is not "active" or "passive" default to passive
newFtp.set_pasv({'passive': True, 'active': False}.get(mode, True))
except socket.error as se:
raise FtpLibraryError('Socket error exception occured.')
except ftplib.all_errors as e:
if connId in self.ftpList:
self.ftp_close(connId)
raise FtpLibraryError(str(e))
except Exception as e:
raise FtpLibraryError(str(e))
if self.printOutput:
logger.info(outputMsg)
def clear_text_data_connection(self, connId='default'):
"""
Switches to a clear text data connection.
Only usable with an FTP TLS connection. No effect if used with a regular ftp connection.
Parameters:
- connId(optional) - connection identifier. By default equals 'default'
"""
outputMsg = ""
thisConn = self.__getConnection(connId)
self.__isTlsConnection(thisConn)
try:
thisConn.prot_c()
except ftplib.all_errors as e:
raise FtpLibraryError(str(e))
if self.printOutput:
logger.info(outputMsg)
return outputMsg
def secure_data_connection(self, connId='default'):
"""
Switches to a secure data connection.
Only usable with an FTP TLS connection. No effect if used with a regular ftp connection.
Parameters:
- connId(optional) - connection identifier. By default equals 'default'
"""
outputMsg = ""
thisConn = self.__getConnection(connId)
self.__isTlsConnection(thisConn)
try:
thisConn.prot_p()
except ftplib.all_errors as e:
raise FtpLibraryError(str(e))
if self.printOutput:
logger.info(outputMsg)
return outputMsg
def get_welcome(self, connId='default'):
"""
Returns welcome message of FTP server.
Parameters:
- connId(optional) - connection identifier. By default equals 'default'
"""
thisConn = self.__getConnection(connId)
outputMsg = ""
try:
outputMsg += thisConn.getwelcome()
except ftplib.all_errors as e:
raise FtpLibraryError(str(e))
if self.printOutput:
logger.info(outputMsg)
return outputMsg
def pwd(self, connId='default'):
"""
Returns the pathname of the current directory on the server.
Parameters:
- connId(optional) - connection identifier. By default equals 'default'
"""
thisConn = self.__getConnection(connId)
outputMsg = ""
try:
outputMsg += thisConn.pwd()
except ftplib.all_errors as e:
raise FtpLibraryError(str(e))
if self.printOutput:
logger.info(outputMsg)
return outputMsg
def cwd(self, directory, connId='default'):
"""
Changes working directory and returns server output. Parameters:
- directory - a path to which working dir should be changed.
- connId(optional) - connection identifier. By default equals 'default'
Example:
| cwd | /home/myname/tmp/testdir | |
| cwd | /home/myname/tmp/testdir | ftp1 |
"""
thisConn = self.__getConnection(connId)
outputMsg = ""
try:
outputMsg += thisConn.cwd(directory)
except ftplib.all_errors as e:
raise FtpLibraryError(str(e))
if self.printOutput:
logger.info(outputMsg)
return outputMsg
def dir(self, connId='default'):
"""
Returns list of raw lines returned as contens of current directory.
Parameters:
- connId(optional) - connection identifier. By default equals 'default'
"""
dirList = []
thisConn = self.__getConnection(connId)
outputMsg = ""
try:
thisConn.dir(dirList.append)
for d in dirList:
outputMsg += str(d) + "\n"
except ftplib.all_errors as e:
raise FtpLibraryError(str(e))
if self.printOutput:
logger.info(outputMsg)
return dirList
def dir_names(self, connId='default'):
"""
Returns list of files (and/or directories) of current directory.
Parameters:
- connId(optional) - connection identifier. By default equals 'default'
"""
files_list = []
thisConn = self.__getConnection(connId)
try:
files_list = thisConn.nlst()
except:
files_list = []
return files_list
def mkd(self, newDirName, connId='default'):
"""
Creates new directory on FTP server. Returns new directory path.
Parameters:
- newDirName - name of a new directory
- connId(optional) - connection identifier. By default equals 'default'
"""
thisConn = self.__getConnection(connId)
outputMsg = ""
try:
outputMsg += str(thisConn.mkd(newDirName))
except ftplib.all_errors as e:
raise FtpLibraryError(str(e))
if self.printOutput:
logger.info(outputMsg)
return outputMsg
def rmd(self, directory, connId='default'):
"""
Deletes directory from FTP server. Returns server output.
Parameters:
- directory - path to a directory to be deleted
- connId(optional) - connection identifier. By default equals 'default'
"""
thisConn = self.__getConnection(connId)
outputMsg = ""
try:
outputMsg += str(thisConn.rmd(directory))
except ftplib.all_errors as e:
raise FtpLibraryError(str(e))
if self.printOutput:
logger.info(outputMsg)
return outputMsg
def download_file(self, remoteFileName, localFilePath=None, connId='default'):
"""
Downloads file from current directory on FTP server in binary mode. If
localFilePath is not given, file is saved in current local directory (by
default folder containing robot framework project file) with the same name
as source file. Returns server output
Parameters:
- remoteFileName - file name on FTP server
- localFilePath (optional) - local file name or path where remote file should be saved.
- connId(optional) - connection identifier. By default equals 'default'
localFilePath variable can have following meanings:
1. file name (will be saved in current default directory);
2. full path (dir + file name)
3. dir path (original file name will be added)
Examples:
| download file | a.txt | | |
| download file | a.txt | b.txt | connId=ftp1 |
| download file | a.txt | D:/rfftppy/tmp | |
| download file | a.txt | D:/rfftppy/tmp/b.txt | |
| download file | a.txt | D:\\rfftppy\\tmp\\c.txt | |
"""
thisConn = self.__getConnection(connId)
outputMsg = ""
localPath = ""
if localFilePath == None:
localPath = remoteFileName
else:
localPath = os.path.normpath(localFilePath)
if os.path.isdir(localPath):
localPath = os.path.join(localPath, remoteFileName)
try:
with open(localPath, 'wb') as localFile:
outputMsg += thisConn.retrbinary("RETR " + remoteFileName, localFile.write)
except ftplib.all_errors as e:
raise FtpLibraryError(str(e))
if self.printOutput:
logger.info(outputMsg)
return outputMsg
def upload_file(self, localFileName, remoteFileName=None, connId='default'):
"""
Sends file from local drive to current directory on FTP server in binary mode.
Returns server output.
Parameters:
- localFileName - file name or path to a file on a local drive.
- remoteFileName (optional) - a name or path containing name under which file should be saved.
- connId(optional) - connection identifier. By default equals 'default'
If remoteFileName agument is not given, local name will be used.
Examples:
| upload file | x.txt | connId=ftp1 |
| upload file | D:/rfftppy/y.txt | |
| upload file | u.txt | uu.txt |
| upload file | D:/rfftppy/z.txt | zz.txt |
| upload file | D:\\rfftppy\\v.txt | |
"""
thisConn = self.__getConnection(connId)
outputMsg = ""
remoteFileName_ = ""
localFilePath = os.path.normpath(localFileName)
if not os.path.isfile(localFilePath):
raise FtpLibraryError("Valid file path should be provided.")
else:
if remoteFileName==None:
fileTuple = os.path.split(localFileName)
if len(fileTuple)==2:
remoteFileName_ = fileTuple[1]
else:
remoteFileName_ = 'defaultFileName'
else:
remoteFileName_ = remoteFileName
try:
outputMsg += thisConn.storbinary("STOR " + remoteFileName_, open(localFilePath, "rb"))
except ftplib.all_errors as e:
raise FtpLibraryError(str(e))
if self.printOutput:
logger.info(outputMsg)
return outputMsg
def size(self, fileToCheck, connId='default'):
"""
Checks size of a file on FTP server. Returns size of a file in bytes (integer).
Parameters:
- fileToCheck - file name or path to a file on FTP server
- connId(optional) - connection identifier. By default equals 'default'
Example:
| ${file1size} = | size | /home/myname/tmp/uu.txt | connId=ftp1 |
| Should Be Equal As Numbers | ${file1size} | 31 | |
Note that the SIZE command is not standardized, but is supported by many
common server implementations.
"""
thisConn = self.__getConnection(connId)
outputMsg = ""
try:
tmpSize = thisConn.size(fileToCheck)
outputMsg += str(tmpSize)
except ftplib.all_errors as e:
raise FtpLibraryError(str(e))
if self.printOutput:
logger.info(outputMsg)
return outputMsg
def rename(self, targetFile, newName, connId='default'):
"""
Renames (actually moves) file on FTP server. Returns server output.
Parameters:
- targetFile - name of a file or path to a file to be renamed
- newName - new name or new path
- connId(optional) - connection identifier. By default equals 'default'
Example:
| rename | tmp/z.txt | /home/myname/tmp/testdir/z.txt |
"""
thisConn = self.__getConnection(connId)
outputMsg = ""
try:
outputMsg += str(thisConn.rename(targetFile, newName))
except ftplib.all_errors as e:
raise FtpLibraryError(str(e))
if self.printOutput:
logger.info(outputMsg)
return outputMsg
def delete(self, targetFile, connId='default'):
"""
Deletes file on FTP server. Returns server output.
Parameters:
- targetFile - file path to be deleted
- connId(optional) - connection identifier. By default equals 'default'
"""
thisConn = self.__getConnection(connId)
outputMsg = ""
try:
outputMsg += str(thisConn.delete(targetFile))
except ftplib.all_errors as e:
raise FtpLibraryError(str(e))
if self.printOutput:
logger.info(outputMsg)
return outputMsg
def send_cmd(self, command, connId='default'):
"""
Sends any command to FTP server. Returns server output.
Parameters:
- command - any valid command to be sent (invalid will result in exception).
- connId(optional) - connection identifier. By default equals 'default'
Example:
| send cmd | HELP |
"""
thisConn = self.__getConnection(connId)
outputMsg = ""
try:
outputMsg += str(thisConn.sendcmd(command))
except ftplib.all_errors as e:
raise FtpLibraryError(str(e))
if self.printOutput:
logger.info(outputMsg)
return outputMsg
def ftp_close(self, connId='default'):
"""
Closes FTP connection. Returns None.
Parameters:
- connId(optional) - connection identifier. By default equals 'default'
"""
thisConn = self.__getConnection(connId)
try:
thisConn.quit()
self.__removeConnection(connId)
except Exception as e:
try:
thisConn.close()
self.__removeConnection(connId)
except ftplib.all_errors as x:
raise FtpLibraryError(str(x))
def __del__(self):
self.ftpList = {}
class FtpLibraryError(Exception):
def __init__(self,msg):
self.msg = msg
def __str__(self):
return self.msg
def main():
import sys
from robotremoteserver import RobotRemoteServer
print("Starting Robot Framework Ftp Library as a remote server ...")
RobotRemoteServer(library=FtpLibrary(), host=sys.argv[1], port=sys.argv[2])
if __name__ == '__main__':
main()