-
Notifications
You must be signed in to change notification settings - Fork 20
/
ftpretty.py
313 lines (264 loc) · 9.71 KB
/
ftpretty.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
""" A simple API wrapper for FTPing files
you should be able to this:
from ftpretty import ftpretty
f = ftpretty(host, user, pass, secure=False, timeout=10)
f.get(remote, local)
f.put(local, remote)
f.list(remote)
f.cd(remote)
f.delete(remote)
f.rename(remote_from, remote_to)
f.close()
"""
from __future__ import print_function
import datetime
from ftplib import FTP, error_perm
import os
import re
from dateutil import parser
from compat import buffer_type, file_type
try:
from ftplib import FTP_TLS
except ImportError:
FTP_TLS = None
class ftpretty(object):
""" A wrapper for FTP connections """
conn = None
port = None
tmp_output = None
relative_paths = set(['.', '..'])
def __init__(self, host, user, password,
secure=False, passive=True, ftp_conn=None, **kwargs):
if 'port' in kwargs:
self.port = kwargs['port']
del kwargs['port']
if ftp_conn:
self.conn = ftp_conn
elif secure and FTP_TLS:
if self.port:
FTP_TLS.port = self.port
self.conn = FTP_TLS(host=host, user=user, passwd=password, **kwargs)
self.conn.prot_p()
else:
if self.port:
FTP.port = self.port
self.conn = FTP(host=host, user=user, passwd=password, **kwargs)
if not passive:
self.conn.set_pasv(False)
def __getattr__(self, name):
""" Pass anything we don't know about, to underlying ftp connection """
def wrapper(*args, **kwargs):
method = getattr(self.conn, name)
return method(*args, **kwargs)
return wrapper
def get(self, remote, local=None):
""" Gets the file from FTP server
local can be:
a file: opened for writing, left open
a string: path to output file
None: contents are returned
"""
if isinstance(local, file_type): # open file, leave open
local_file = local
elif local is None: # return string
local_file = buffer_type()
else: # path to file, open, write/close return None
local_file = open(local, 'wb')
self.conn.retrbinary("RETR %s" % remote, local_file.write)
if isinstance(local, file_type):
pass
elif local is None:
contents = local_file.getvalue()
local_file.close()
return contents
else:
local_file.close()
return None
def put(self, local, remote, contents=None, quiet=False):
""" Puts a local file (or contents) on to the FTP server
local can be:
a string: path to inpit file
a file: opened for reading
None: contents are pushed
"""
remote_dir = os.path.dirname(remote)
remote_file = os.path.basename(local)\
if remote.endswith('/') else os.path.basename(remote)
if contents:
# local is ignored if contents is set
local_file = buffer_type(contents)
elif isinstance(local, file_type):
local_file = local
else:
local_file = open(local, 'rb')
current = self.conn.pwd()
self.descend(remote_dir, force=True)
size = 0
try:
self.conn.storbinary('STOR %s' % remote_file, local_file)
size = self.conn.size(remote_file)
except:
if not quiet:
raise
finally:
local_file.close()
self.conn.cwd(current)
return size
def upload_tree(self, src, dst, ignore=None):
"""Recursively upload a directory tree.
Although similar to shutil.copytree we don't follow symlinks.
"""
names = os.listdir(src)
if ignore is not None:
ignored_names = ignore(src, names)
else:
ignored_names = set()
try:
dst = dst.replace('\\', '/')
self.conn.mkd(dst)
except error_perm:
pass
errors = []
for name in names:
if name in ignored_names:
continue
src_name = os.path.join(src, name)
dst_name = os.path.join(dst, name)
try:
if os.path.islink(src_name):
pass
elif os.path.isdir(src_name):
self.upload_tree(src_name, dst_name, ignore)
else:
# Will raise a SpecialFileError for unsupported file types
self.put(src_name, dst_name)
except Exception as why:
errors.append((src_name, dst_name, str(why)))
return dst
def list(self, remote='.', extra=False, remove_relative_paths=False):
""" Return directory list """
if extra:
self.tmp_output = []
self.conn.dir(remote, self._collector)
directory_list = split_file_info(self.tmp_output)
else:
directory_list = self.conn.nlst(remote)
if remove_relative_paths:
return list(filter(self.is_not_relative_path, directory_list))
return directory_list
def is_not_relative_path(self, path):
if isinstance(path, dict):
return path.get('name') not in self.relative_paths
else:
return path not in self.relative_paths
def descend(self, remote, force=False):
""" Descend, possibly creating directories as needed """
remote_dirs = remote.split('/')
for directory in remote_dirs:
try:
self.conn.cwd(directory)
except Exception:
if force:
self.conn.mkd(directory)
self.conn.cwd(directory)
return self.conn.pwd()
def delete(self, remote):
""" Delete a file from server """
try:
self.conn.delete(remote)
except Exception:
return False
else:
return True
def cd(self, remote):
""" Change working directory on server """
try:
self.conn.cwd(remote)
except Exception:
return False
else:
return self.pwd()
def pwd(self):
""" Return the current working directory """
return self.conn.pwd()
def rename(self, remote_from, remote_to):
""" Rename a file on the server """
return self.conn.rename(remote_from, remote_to)
def mkdir(self, new_dir):
""" Create directory on the server """
return self.conn.mkd(new_dir)
def close(self):
""" End the session """
try:
self.conn.quit()
except Exception:
self.conn.close()
def _collector(self, line):
""" Helper for collecting output from dir() """
self.tmp_output.append(line)
def split_file_info(fileinfo):
""" Parse sane directory output usually ls -l
Adapted from https://gist.github.com/tobiasoberrauch/2942716
"""
current_year = datetime.datetime.now().strftime('%Y')
files = []
unix_format = re.compile(
r'^([\-dbclps])' + # Directory flag [1]
r'((?:[r-][w-][-xsStT]){3})\s+' + # Permissions [2]
r'(\d+)\s+' + # Number of items [3]
r'([a-zA-Z0-9_-]+)\s+' + # File owner [4]
r'([a-zA-Z0-9_-]+)\s+' + # File group [5]
r'(\d+)\s+' + # File size in bytes [6]
r'(\w{3}\s+\d{1,2})\s+' + # 3-char month and 1/2-char day of the month [7]
r'(\d{1,2}:\d{1,2}|\d{4})\s+' + # Time or year (need to check conditions) [+= 7]
r'(.+)$' # File/directory name [8]
)
# not exactly sure what format this, but seems windows-esque
# attempting to address issue: https://github.com/codebynumbers/ftpretty/issues/34
# can get better results with more data.
windows_format = re.compile(
r'(\d{2})-(\d{2})-(\d{2})\s+' + # month/day/2-digit year (assuming after 2000)
r'(\d{2}):(\d{2})([AP])M\s+' + # time
r'(\d+)\s+' + # file size
r'(.+)$' # filename
)
for line in fileinfo:
if unix_format.match(line):
parts = unix_format.split(line)
date = parts[7]
time = parts[8] if ':' in parts[8] else '00:00'
year = parts[8] if ':' not in parts[8] else current_year
dt_obj = parser.parse("%s %s %s" % (date, year, time))
files.append({
'directory': parts[1],
'perms': parts[2],
'items': parts[3],
'owner': parts[4],
'group': parts[5],
'size': int(parts[6]),
'date': date,
'time': time,
'year': year,
'name': parts[9],
'datetime': dt_obj
})
elif windows_format.match(line):
parts = windows_format.split(line)
hour = int(parts[4])
hour += 12 if parts[6] == 'P' else 0
year = int(parts[3]) + 2000
dt_obj = datetime.datetime(year, int(parts[1]), int(parts[2]), hour, int(parts[5]), 0)
files.append({
'directory': None,
'perms': None,
'items': None,
'owner': None,
'group': None,
'size': int(parts[7]),
'date': "{}-{}-{}".format(*parts[1:4]),
'time': "{}:{}{}".format(*parts[4:7]),
'year': year,
'name': parts[8],
'datetime': dt_obj
})
return files