def redirect_internal(self, url, fp, errcode, errmsg, headers, data):
if 'location' in headers:
newurl = headers['location']
elif 'uri' in headers:
newurl = headers['uri']
else:
return
void = fp.read()
fp.close()
# In case the server sent a relative URL, join with original:
newurl = basejoin(self.type + ":" + url, newurl)
# For security reasons we do not allow redirects to protocols
# other than HTTP, HTTPS or FTP.
newurl_lower = newurl.lower()
if not (newurl_lower.startswith('http://') or
newurl_lower.startswith('https://') or
newurl_lower.startswith('ftp://')):
raise IOError('redirect error', errcode,
errmsg + " - Redirection to url '%s' is not allowed" %
newurl,
headers)
return self.open(newurl)
python类FTP的实例源码
def create_folder(folder):
try:
folder = xbmc.makeLegalFilename(folder)
control.makeFile(folder)
try:
if not 'ftp://' in folder: raise Exception()
from ftplib import FTP
ftparg = re.compile('ftp://(.+?):(.+?)@(.+?):?(\d+)?/(.+/?)').findall(folder)
ftp = FTP(ftparg[0][2], ftparg[0][0], ftparg[0][1])
try:
ftp.cwd(ftparg[0][4])
except:
ftp.mkd(ftparg[0][4])
ftp.quit()
except:
pass
except:
pass
def setup_module(module):
# enter test directory
os.chdir('pycoal/tests')
# download spectral library over FTP if necessary
if not os.path.isfile(libraryFilenames[0]) and \
not os.path.isfile(libraryFilenames[1]):
ftp_url = "ftpext.cr.usgs.gov"
ftp_dir = "pub/cr/co/denver/speclab/pub/spectral.library/splib06.library/Convolved.libraries/"
ftp = ftplib.FTP(ftp_url)
ftp.login()
ftp.cwd(ftp_dir)
for f in libraryFilenames:
with open("" + f, "wb") as lib_f:
ftp.retrbinary('RETR %s' % f, lib_f.write)
# tear down test module after running tests
def update_sideshow_file(fname,
server_fname,
server=SIDESHOW_SERVER,
temp_path=gettempdir()):
"""
Update the JPL side show file stored locally at *fname*. The
remote file is accessed via FTP on *server* at *server_fname*. The
path *temp_path* is used to store intermediate files. Return
*fname*.
"""
dest_fname = replace_path(temp_path, server_fname)
logger.info('opening connection to {}'.format(server))
with closing(FTP(server)) as ftp, open(dest_fname, 'w') as fid:
logger.info('logging in')
ftp.login()
logger.info('writing to {}'.format(dest_fname))
ftp.retrbinary('RETR ' + server_fname, fid.write)
logger.info('uncompressing file to {}'.format(fname))
with GzipFile(dest_fname) as gzip_fid, open(fname, 'w') as fid:
fid.write(gzip_fid.read())
return fname
def workhorse(ipaddr, user, word):
user = user.replace("\n","")
word = word.replace("\n","")
try:
print "-"*12
print "User:",user,"Password:",word
ftp = FTP(ipaddr)
ftp.login(user, word)
ftp.retrlines('LIST')
print "\t\n[!] Login successful:",user, word
if txt != None:
save_file.writelines(user+" : "+word+" @ "+ipaddr+":21\n")
ftp.quit()
sys.exit(2)
except (ftplib.all_errors), msg:
#print "[-] An error occurred:", msg
pass
def brute(ipaddr):
print "-"*30
print "\n[+] Attempting BruteForce:",ipaddr,"\n"
try:
f = FTP(ipaddr)
print "[+] Response:",f.getwelcome()
except (ftplib.all_errors):
pass
try:
print "\n[+] Checking for anonymous login:",ipaddr,"\n"
ftp = FTP(ipaddr)
ftp.login()
ftp.retrlines('LIST')
print "\t\n[!] Anonymous login successful!!!\n"
if txt != None:
save_file.writelines("Anonymous:"+ipaddr+":21\n")
ftp.quit()
except (ftplib.all_errors):
print "[-] Anonymous login unsuccessful\n"
for user in users:
for word in words:
work = threading.Thread(target = workhorse, args=(ipaddr, user, word)).start()
time.sleep(1)
def redirect_internal(self, url, fp, errcode, errmsg, headers, data):
if 'location' in headers:
newurl = headers['location']
elif 'uri' in headers:
newurl = headers['uri']
else:
return
fp.close()
# In case the server sent a relative URL, join with original:
newurl = basejoin(self.type + ":" + url, newurl)
# For security reasons we do not allow redirects to protocols
# other than HTTP, HTTPS or FTP.
newurl_lower = newurl.lower()
if not (newurl_lower.startswith('http://') or
newurl_lower.startswith('https://') or
newurl_lower.startswith('ftp://')):
raise IOError('redirect error', errcode,
errmsg + " - Redirection to url '%s' is not allowed" %
newurl,
headers)
return self.open(newurl)
def __init__(self, hostname, root_path, base_url,
username=None, password=None, passive=True, secure=False, **kwargs):
if isinstance(hostname, FTP):
self.ftp_client = hostname
else: # pragma: nocover
if secure:
self.ftp_client = FTP_TLS(host=hostname, user=username, passwd=password, **kwargs)
# noinspection PyUnresolvedReferences
self.ftp_client.prot_p()
else:
self.ftp_client = FTP(host=hostname, user=username, passwd=password, **kwargs)
self.ftp_client.set_pasv(passive)
self.root_path = root_path
self.base_url = base_url.rstrip('/')
def get_all_species(self):
import tempfile
outfile = tempfile.mktemp() + '.txt.gz'
try:
self.logger.info('Downloading "species.txt.gz"...')
out_f = open(outfile, 'wb')
ftp = FTP(self.__class__.ENSEMBL_FTP_HOST)
ftp.login()
species_file = '/pub/release-%s/mysql/ensembl_production_%s/species.txt.gz' % (self.release, self.release)
ftp.retrbinary("RETR " + species_file, out_f.write)
out_f.close()
self.logger.info('Done.')
#load saved file
self.logger.info('Parsing "species.txt.gz"...')
species_li = tab2list(outfile, (1, 2, 7), header=0) # db_name,common_name,taxid
species_li = [x[:-1] + [is_int(x[-1]) and int(x[-1]) or None] for x in species_li]
# as of ensembl 87, there are also mouse strains. keep only the "original" one
species_li = [s for s in species_li if not s[0].startswith("mus_musculus_")]
self.logger.info('Done.')
finally:
os.remove(outfile)
pass
return species_li
def ftp_size(host_name, path):
from ftplib import FTP
try:
ftp = FTP(host_name)
except Exception as e:
print(e)
return -1
try:
ftp.login()
ftp.voidcmd('TYPE I')
size = ftp.size(path)
ftp.quit()
except Exception as e:
print(e)
return 0
return size
def list_children(self, path):
"""
Yield all direct children of the given root-relative path, as root-
relative paths. If the path refers to a file, there will be no children.
"""
if len(path) > 0 and not path.endswith("/"):
# We need a trailing slash after a real directory name for urljoin
# to work later
path = path + "/"
# Strip leading slashes from the input path, so we always look inside
# our base path.
path = path.lstrip("/")
# Construct the path to actually go to on the FTP server
ftp_path = urlparse.urljoin(self.base_path, path)
Logger.debug("Listing {}".format(ftp_path))
for child in robust_nlst(self.connection, ftp_path):
# For every child, build a root-relative URL
yield urlparse.urljoin(path, child)
def _download_latest_clinvar_xml(self, dest_dir):
ftp = FTP('ftp.ncbi.nlm.nih.gov')
ftp.login()
ftp.cwd(CV_XML_DIR)
# sort just in case the ftp lists the files in random order
cv_xml_w_date = sorted(
[f for f in ftp.nlst() if re.match(CV_XML_REGEX, f)])
if len(cv_xml_w_date) == 0:
raise CommandError('ClinVar reporting zero XML matching' +
' regex: \'{0}\' in directory {1}'.format(
CV_XML_REGEX, CV_XML_DIR))
ftp_xml_filename = cv_xml_w_date[-1]
dest_filepath = os.path.join(dest_dir, ftp_xml_filename)
with open(dest_filepath, 'w') as fh:
ftp.retrbinary('RETR {0}'.format(ftp_xml_filename), fh.write)
return dest_filepath, ftp_xml_filename
def get_data_Weather():
while True:
print("Input the data for the Wunderground weather API.\n")
API_KEY = input("API Key:\n")
COUNTRY = input("Country:\n")
CITY = input("City:\n")
CITY_code = check_weather(API_KEY,COUNTRY, CITY)
if CITY_code == False:
if y_n("Retry?") == False:
raise Exception("User abort on Weather Data select.")
else:
break
while True:
print("Input the data for the DWD FTP Server.\n")
dwdname = input("Username:\n")
dwdpass = input("Password:\n")
if not check_dwdftp(dwdname, dwdpass):
if y_n("Retry?") == False:
raise Exception("User abort on DWD FTP Server data input.")
else:
break
return InputWeather(API_KEY, CITY_code,dwdname,dwdpass)
def redirect_internal(self, url, fp, errcode, errmsg, headers, data):
if 'location' in headers:
newurl = headers['location']
elif 'uri' in headers:
newurl = headers['uri']
else:
return
fp.close()
# In case the server sent a relative URL, join with original:
newurl = basejoin(self.type + ":" + url, newurl)
# For security reasons we do not allow redirects to protocols
# other than HTTP, HTTPS or FTP.
newurl_lower = newurl.lower()
if not (newurl_lower.startswith('http://') or
newurl_lower.startswith('https://') or
newurl_lower.startswith('ftp://')):
raise IOError('redirect error', errcode,
errmsg + " - Redirection to url '%s' is not allowed" %
newurl,
headers)
return self.open(newurl)
def set_aspera_variables(filepath):
try:
parser = SafeConfigParser()
parser.read(filepath)
global ASPERA_BIN
ASPERA_BIN = parser.get('aspera', 'ASPERA_BIN')
global ASPERA_PRIVATE_KEY
ASPERA_PRIVATE_KEY = parser.get('aspera', 'ASPERA_PRIVATE_KEY')
if not os.path.exists(ASPERA_PRIVATE_KEY):
print 'Private key file ({0}) does not exist. Defaulting to FTP transfer'.format(ASPERA_PRIVATE_KEY)
return False
global ASPERA_SPEED
ASPERA_SPEED = parser.get('aspera', 'ASPERA_SPEED')
global ASPERA_OPTIONS
ASPERA_OPTIONS = parser.get('aspera', 'ASPERA_OPTIONS')
return True
except Exception as e:
sys.stderr.write("ERROR: cannot read aspera settings from {0}.\n".format(filepath))
sys.stderr.write("{0}\n".format(e))
sys.exit(1)
def set_aspera(aspera_filepath):
aspera = True
if aspera_filepath is not None:
if os.path.exists(aspera_filepath):
aspera = set_aspera_variables(aspera_filepath)
else:
print 'Cannot find {0} file, defaulting to FTP transfer'.format(aspera_filepath)
aspera = False
elif os.environ.get('ENA_ASPERA_INIFILE'):
aspera = set_aspera_variables(os.environ.get('ENA_ASPERA_INIFILE'))
else:
if os.path.exists(os.path.join(enaBrowserTools_path, 'aspera_settings.ini')):
aspera = set_aspera_variables(os.path.join(enaBrowserTools_path, 'aspera_settings.ini'))
else:
print 'Cannot find aspera_settings.ini file, defaulting to FTP transfer'
aspera = False
return aspera
def set_aspera_variables(filepath):
try:
parser = SafeConfigParser()
parser.read(filepath)
global ASPERA_BIN
ASPERA_BIN = parser.get('aspera', 'ASPERA_BIN')
global ASPERA_PRIVATE_KEY
ASPERA_PRIVATE_KEY = parser.get('aspera', 'ASPERA_PRIVATE_KEY')
if not os.path.exists(ASPERA_PRIVATE_KEY):
print('Private key file ({0}) does not exist. Defaulting to FTP transfer'.format(ASPERA_PRIVATE_KEY))
return False
global ASPERA_SPEED
ASPERA_SPEED = parser.get('aspera', 'ASPERA_SPEED')
global ASPERA_OPTIONS
ASPERA_OPTIONS = parser.get('aspera', 'ASPERA_OPTIONS')
return True
except Exception as e:
sys.stderr.write("ERROR: cannot read aspera settings from {0}.\n".format(filepath))
sys.stderr.write("{0}\n".format(e))
sys.exit(1)
def set_aspera(aspera_filepath):
aspera = True
if aspera_filepath is not None:
if os.path.exists(aspera_filepath):
aspera = set_aspera_variables(aspera_filepath)
else:
print('Cannot find {0} file, defaulting to FTP transfer'.format(aspera_filepath))
aspera = False
elif os.environ.get('ENA_ASPERA_INIFILE'):
aspera = set_aspera_variables(os.environ.get('ENA_ASPERA_INIFILE'))
else:
if os.path.exists(os.path.join(enaBrowserTools_path, 'aspera_settings.ini')):
aspera = set_aspera_variables(os.path.join(enaBrowserTools_path, 'aspera_settings.ini'))
else:
print('Cannot find aspera_settings.ini file, defaulting to FTP transfer')
aspera = False
return aspera
def redirect_internal(self, url, fp, errcode, errmsg, headers, data):
if 'location' in headers:
newurl = headers['location']
elif 'uri' in headers:
newurl = headers['uri']
else:
return
fp.close()
# In case the server sent a relative URL, join with original:
newurl = basejoin(self.type + ":" + url, newurl)
# For security reasons we do not allow redirects to protocols
# other than HTTP, HTTPS or FTP.
newurl_lower = newurl.lower()
if not (newurl_lower.startswith('http://') or
newurl_lower.startswith('https://') or
newurl_lower.startswith('ftp://')):
raise IOError('redirect error', errcode,
errmsg + " - Redirection to url '%s' is not allowed" %
newurl,
headers)
return self.open(newurl)
def _get_ftp_connection(self):
for _ in range(self.n_tries):
try:
ftp = ftplib.FTP("ftp.ncdc.noaa.gov")
except ftplib.all_errors as e:
logger.warn("FTP connection issue: %s", e)
else:
logger.info(
"Successfully established connection to ftp.ncdc.noaa.gov."
)
try:
ftp.login()
except ftplib.all_errors as e:
logger.warn("FTP login issue: %s", e)
else:
logger.info(
"Successfully logged in to ftp.ncdc.noaa.gov."
)
return ftp
raise RuntimeError("Couldn't establish an FTP connection.")
def run(config, status):
"""
Job to recursively download a directory from an FTP server
This will overwrite any files that are in the dest_root directory
"""
ftp_addr = config.get(KEYS.SERVER_ADDRESS, "localhost")
ftp_port = config.get(KEYS.SERVER_PORT, 21)
ftp_root = config.get(KEYS.FTP_ROOT, "/")
dest_root = config.get(KEYS.DEST_ROOT, "C:\\temp\\")
user = config.get(KEYS.USERNAME, "")
password = config.get(KEYS.PASSWORD, "")
try:
ftp_session = FTP()
ftp_session.connect(ftp_addr, ftp_port)
ftp_session.login(user, password)
except socket.gaierror, e:
status.update({"error": str(e)})
logger.error(e)
return
logger.debug("connected {0}")
download_files(ftp_session, ftp_root, dest_root, status)
ftp_session.close()
def get_ftp_instance(base_url):
"""
Get ftplib.FTP object that is connected to base_url.
Returns
-------
ftplib.FTP
FTP object connected to base_url.
"""
try:
ftp = ftplib.FTP(base_url)
ftp.login()
return ftp
except Exception:
raise ConnectionError('Problems connecting to ENSEMBL FTP server.')
# pylint: disable=redefined-outer-name
def create_folder(folder):
try:
folder = xbmc.makeLegalFilename(folder)
control.makeFile(folder)
try:
if not 'ftp://' in folder: raise Exception()
from ftplib import FTP
ftparg = re.compile('ftp://(.+?):(.+?)@(.+?):?(\d+)?/(.+/?)').findall(folder)
ftp = FTP(ftparg[0][2], ftparg[0][0], ftparg[0][1])
try:
ftp.cwd(ftparg[0][4])
except:
ftp.mkd(ftparg[0][4])
ftp.quit()
except:
pass
except:
pass
def attemptLogin(self, credential):
success = False
Hive.attemptLogin(self, credential)
username = credential.username
password = credential.password
host = credential.host
try:
self.ftp = FTP(host)
result = self.ftp.login(username,password)
# If result then this was a successful login
if result:
success = True
self.ftp.close()
except:
pass
return success
# function: setup
# description: Prepares this Hive for its attack, *NOTE* This must be called before start is called
def try_login(custom_users, custom_passwords, host, port):
for user in custom_users:
for password in custom_passwords:
try:
con = ftplib.FTP(timeout=3.5)
con.connect(host, port)
ans = con.login(user,password)
if "230" in ans:
anon_login = "Success ({} - {})".format(user, password)
dir_listing = get_directory_listing(con)
return (anon_login, dir_listing)
else:
con.quit()
con.close()
continue
except socket.timeout:
anon_login = "Timed out"
return (anon_login, None)
except Exception as e:
anon_login = "Disallowed"
return (anon_login, None)
def create_folder(folder):
try:
folder = xbmc.makeLegalFilename(folder)
control.makeFile(folder)
try:
if not 'ftp://' in folder: raise Exception()
from ftplib import FTP
ftparg = re.compile('ftp://(.+?):(.+?)@(.+?):?(\d+)?/(.+/?)').findall(folder)
ftp = FTP(ftparg[0][2], ftparg[0][0], ftparg[0][1])
try:
ftp.cwd(ftparg[0][4])
except:
ftp.mkd(ftparg[0][4])
ftp.quit()
except:
pass
except:
pass
def main():
p = argparse.ArgumentParser(usage='''
python ftp.py --host 127.0.0.1
python ftp.py --host 127.0.0.1 --file password.txt
python ftp.py --host 192.168.4 --file password.txt -C Scan''',description='Crack FTP Password')
p.add_argument('-host','--host',help='Input TarGet IP or Scan C network :192.168.4')
p.add_argument('-f','--file',help='Input Password File')
p.add_argument('-C',help='Scan C network')
args = p.parse_args()
host = args.host
password = args.file
C_Network = args.C
if password == None or password == None:
anon_login(host)
elif C_Network == "Scan":
ip_C(host,password)
else:
CrackFtpLogin(host,password)
def redirect_internal(self, url, fp, errcode, errmsg, headers, data):
if 'location' in headers:
newurl = headers['location']
elif 'uri' in headers:
newurl = headers['uri']
else:
return
fp.close()
# In case the server sent a relative URL, join with original:
newurl = basejoin(self.type + ":" + url, newurl)
# For security reasons we do not allow redirects to protocols
# other than HTTP, HTTPS or FTP.
newurl_lower = newurl.lower()
if not (newurl_lower.startswith('http://') or
newurl_lower.startswith('https://') or
newurl_lower.startswith('ftp://')):
raise IOError('redirect error', errcode,
errmsg + " - Redirection to url '%s' is not allowed" %
newurl,
headers)
return self.open(newurl)
def ftp(config, host):
"""
Check a hosts FTP service
:param config: dictionary containing settings
config['vars']['ftp_timeout']: The timeout in seconds to wait for the
ftp connection to complete by
:param host: The host to connect to over FTP
:return: 3-tuple of (success, name, message)
success: Boolean value indicating if there is a problem or not
name: DNS name
message: String describing the status
"""
name = host
try:
ftp_conn = FTP(host=host,
timeout=config['vars']['ftp_timeout'])
except Exception as e:
return False, name, "Exception %s %s" % (e.__class__, e)
welcome = ftp_conn.getwelcome()
ftp_conn.quit()
return True, name, "FTP ok %s" % welcome
def getftpconnect():
ftp_server = '121.69.75.194'
username = 'wac'
password = '8112whz'
ftp = FTP()
#ftp.set_debuglevel(2) # ??????2???????
ftp.connect(ftp_server, 22) # ??
ftp.login(username, password) # ?????????????????
print ftp.getwelcome()
return ftp