-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathftpscanner.py
115 lines (90 loc) · 3.49 KB
/
ftpscanner.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
import ftplib
import socket
import tempfile
class FTPScanner:
__conn = None
__logging = None
is_connected = False
def __init__(self, siteurl, port=21, logging=False):
self.__logging = logging
try:
self.__conn = ftplib.FTP()
self.__conn.connect(siteurl, port)
self.__conn.login() # user anonymous, passwd anonymous@
self.__conn.set_pasv(False)
self.is_connected = True
except ftplib.error_perm as e:
if self.__logging: print "\tServer Error (%s): %s" % (siteurl, e)
except socket.error as e:
if self.__logging: print "\t%s" % e
def close(self):
if self.__conn is not None:
self.__conn.quit()
self.is_connected = False
def get_welcome(self):
if self.__conn is not None:
return self.__conn.getwelcome()
return ""
def change_working_dir(self, path):
if self.__conn is not None:
self.__conn.cwd(path)
def get_directory_list(self):
if self.__conn is None:
return []
dirs = []
def append_dirs_mlsd(item):
parts = item.split(';')
filename = parts[-1]
for part in parts:
if part.startswith('type') and part.split('=')[-1] == 'dir':
dirs.append(filename.strip())
def append_dirs(item):
if item.startswith('d'):
parts = item.split()
if parts[-1] not in ['.', '..']:
dirs.append(' '.join(parts[8:]))
try:
try:
self.__conn.retrlines('MLSD', append_dirs_mlsd)
except ftplib.error_perm as e:
# MLSD likely not supported, fallback to LIST
self.__conn.retrlines('LIST', append_dirs)
except ftplib.error_temp as e:
if self.__logging: print "\t%s" % e
return dirs
def get_file_list(self):
if self.__conn is None:
return []
files = []
def append_files(item):
if not item.startswith('d'):
parts = item.split()
files.append(' '.join(parts[8:]))
try:
try:
self.__conn.retrlines('NLIST', files.append)
except ftplib.error_perm as e:
# NLIST likely not supported, fallback to LIST
self.__conn.retrlines('LIST', append_files)
except ftplib.error_temp as e:
if self.__logging: print "\t%s" % e
return files
def download_file(self, filepath, binary=True):
if self.__conn is None:
return None
if filepath.startswith('/'):
filepath = filepath[1:]
try:
if binary:
tmp = tempfile.NamedTemporaryFile(mode='w+b', delete=False)
self.__conn.retrbinary('RETR ' + filepath, tmp.write)
else:
tmp = tempfile.NamedTemporaryFile(mode='w+', delete=False)
self.__conn.storlines('RETR ' + filepath, tmp.write)
except ftplib.error_temp as e:
if self.__logging: print "\t%s" % e
except ftplib.error_perm as e:
if self.__logging: print "\t%s" % e
tmpname = tmp.name
tmp.close()
return tmpname