def connect_ftps(): #Connect to the server print("Step 1") if SECURE_CONN == '1': ftps = FTP_TLS(SERVER) print("Secure connection") else: ftps = FTP(SERVER) print("Unsecure connection") print("Step 2") ftps.set_debuglevel(2) print("Step 3") ftps.set_pasv(False) print("Step 4") ftps.connect(port=int(PORT), timeout=160) print("Step 5") ftps.login(USER, PASS) print("Step 6") ftps.cwd(TARGET_DIR) print("Step 7") ftps.set_pasv(True) print("Step 8") #Set up the secure connection only in FTPS mode if SECURE_CONN == '1': ftps.prot_p() else: pass #ftps.ccc() return ftps
def downloadXmlTranscripts(self): ftp = FTP_TLS() ftp.debugging = 2 ftp.connect(self.ftp_server,990) print ftp ftp.login(self.ftp_user,self.ftp_pass) print(ftp)
def ftps_connect(host): ftps = FTP_TLS() ftps.ssl_version = ssl.PROTOCOL_SSLv23 ftps.connect(host) ftps.login(settings.NC_FTP_USER, settings.NC_FTP_PASSWORD) ftps.prot_p() return ftps
def get_ftp_list(): ftp = FTP_TLS() ftp.connect(host, port) ftp.set_debuglevel(2) ftp.login("account_id", "account_password") files, dir = get_list_ftp(ftp, "/") return files, dir
def upload_to_ftp(root_dir, upload_path): ftp = FTP_TLS() ftp.connect(host, port) ftp.set_debuglevel(2) ftp.login("account_id", "account_password") files, directories = get_list_local(upload_path) directory_name = os.path.dirname(upload_path) directory_name = os.path.basename(directory_name) root_dir = root_dir + directory_name + "/" directories.insert(0, "") for directory in directories: path = directory.replace(upload_path, "").replace("\\", "/") path = root_dir + path # for fName in ftp.nlst(): # print(fName) # if folderName in ftp.nlst(): # continue try: ftp.mkd(path) except: continue print("Make directory is " + path) for file in files: path = file.replace(upload_path, "").replace("\\", "/") with open(file, "rb") as localfile: path = root_dir + path ftp.storbinary('STOR ' + path, localfile) print("Upload file is " + path) print("done upload")
def Push( FtpServer, Username, Password, uploadlist = FilesToPut, port = 21, passive = False, StartTls = False ): print "Login to %s:%s using %s:%s (%s%s)"%(FtpServer, port, Username, 'xxx', 'passive' if passive else 'active', '/tls' if StartTls else '') if StartTls: ftp = FTP_TLS() else: ftp = FTP() #ftp.set_debuglevel(2) ftp.connect( FtpServer, port ) ftp.login( Username, Password ) # user anonymous, passwd anonymous@ ftp.set_pasv( passive ) if StartTls: ftp.prot_p() for f in uploadlist: print "uploading %s"%f fp = open( f, 'rb') ftp.storbinary('STOR %s'%os.path.basename(f), fp) # send the file ftp.quit()
def downloadSarZIP(value, ftpParams): ftps = FTP_TLS() #ftps.set_debuglevel(2) ftps.connect(ftpParams.host) ftps.sendcmd('USER ' + ftpParams.user) ftps.sendcmd('PASS ' + ftpParams.password) list_of_files = [] checkFile = [] ftps.retrlines("NLST", list_of_files.append) # ...or use the existing helper # list_of_files = ftps.nlst() dest_dir = "./" # download files from ftp for name in list_of_files: if fnmatch.fnmatch(name, value + "_*"): checkFile.append(name) with open(os.path.join(dest_dir, name), "wb") as f: ftps.retrbinary("RETR {}".format(name), f.write) #delete files from ftp for name in list_of_files: if fnmatch.fnmatch(name, value + "_*"): ftps.delete(name) ftps.quit() return checkFile
def _open_ftp(self): # type: () -> FTP """Open a new ftp object.""" _ftp = FTP_TLS() if self.tls else FTP() _ftp.set_debuglevel(0) with ftp_errors(self): _ftp.connect(self.host, self.port, self.timeout) _ftp.login(self.user, self.passwd, self.acct) try: _ftp.prot_p() # type: ignore except AttributeError: pass self._features = {} try: feat_response = _decode(_ftp.sendcmd("FEAT"), "latin-1") except error_perm: # pragma: no cover self.encoding = "latin-1" else: self._features = self._parse_features(feat_response) self.encoding = "utf-8" if "UTF8" in self._features else "latin-1" if not PY2: _ftp.file = _ftp.sock.makefile( # type: ignore "r", encoding=self.encoding) _ftp.encoding = self.encoding self._welcome = _ftp.welcome return _ftp
def getfilelist(server, port, user, password, db): sqliteconnection = sqlite3.connect(db) sqlitecursor = sqliteconnection.cursor() sqlitecursor.execute('''CREATE TABLE IF NOT EXISTS files (date int, name text, CONSTRAINT 'id_UNIQUE' UNIQUE ('name'))''') sqliteconnection.commit() ftpsconnection = FTP_TLS() ftpsconnection.connect(server, port) ftpsconnection.auth() ftpsconnection.prot_p() ftpsconnection.login(user, password) ftpsconnection.prot_p() rootfiles = ftpsconnection.nlst() for i in range(0,5): episodes = ftpsconnection.nlst(rootfiles[i]) for episode in episodes: sqlitecursor.execute('''INSERT OR IGNORE INTO files VALUES ("%(date)d", "%(folder)s")''' % {'date': time.time(), 'folder': ("/" + rootfiles[i] + "/" + episode) } ) sqliteconnection.commit() sqliteconnection.close() ftpsconnection.quit() ftpsconnection.close()
def send_to_ftp(self, start=None, stop=None): now = self.datetime_localized(fields.Datetime.now(self)) start = start or now.replace(hour=0, minute=0, second=0) stop = stop or start + timedelta(days=1) host = self.env.user.company_id.ftp_host port = self.env.user.company_id.ftp_port user = self.env.user.company_id.ftp_user passwd = self.env.user.company_id.ftp_passwd ftp_tls = False ftp = FTP_TLS() if ftp_tls else FTP() try: ftp.connect(host, port) ftp.login(user, passwd) except: _logger.error('Unable to reach FTP server') else: stocklocations = self.get_stocklocations_file() mtsskus = self.get_mtsskus_file() transactions = self.get_transactions_file(str(start), str(stop)) status = self.get_status_file() ftp.storbinary('STOR ' + stocklocations[0], BytesIO(stocklocations[1])) ftp.storbinary('STOR ' + mtsskus[0], BytesIO(mtsskus[1])) ftp.storbinary('STOR ' + transactions[0], BytesIO(transactions[1])) ftp.storbinary('STOR ' + status[0], BytesIO(status[1])) finally: ftp.close()
def connect_ftps(): """ FTP over TLS NOte: do NOT enable 'Require TLS session resumption on data connection when using PROT P', or you will get exception 'ssl.SSLEOFError: EOF occurred in violation of protocol (_ssl.c:727)' or server side will show '450 TLS session of data connection has not resumed or the session does not match the control connection' :return: """ ftps = FTP_TLS() # ftps.set_debuglevel(2) ssl_version_stack = [ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv3] tls_version_stack = [ssl.PROTOCOL_TLSv1_2, ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLS] is_connected = False for ssl_version in ssl_version_stack + tls_version_stack: # also can use list.extend() or list slice instead of + ftps.ssl_version = ssl_version try: ftps.connect(host=server, port=port) is_connected = True break except socket.timeout: continue except socket.error as e: # such as '10061', '[Errno 10061] Connection refused.' print(str(e), socket.errorTab.get(int(str(e).strip()[7:-1]))) continue else: if not is_connected: raise RuntimeError("No SSL/TLS supported on ftp server, does server misconfigured?") ftps.login(user=username, passwd=password) ftps.prot_p() # 'Force PROT P to encrypt file transfers when using FTP TLS' return ftps
def get_session_ftps(host, login=None, password=None, port=21, auth=False, protocol=True): """ Creates connection with FTPS server :param host: host of FTPS server :param login: user's name :param password: password for user :param port: port of FTPS server :param auth: if it is true sets up secure control connection by using TLS/SSL :param protocol: if it is true sets up secure data connection else sets up clear text data connection :return: FTPConnector :type host: str :type login: str :type password: str :type port: int :type auth: bool :type protocol: bool :rtype: FTPConnector """ try: ftp = FTP_TLS() ftp.connect(host, port) ftp.login(login, password) if protocol: ftp.prot_p() else: ftp.prot_c() if auth: ftp.auth() return FTPConnector(ftp) except error_perm, exp: raise FTPConnectorError( exp.message )
class ExplicitTLS(Configuration): """ This class includes methods to allow establishing a secure Explicit FTP secure connection to the One Scotland Gazetteer FTP """ def __init__(self): Configuration.__init__(self) self.host = self.get_configuration_for('ftp', 'host') self.port = int(self.get_configuration_for('ftp', 'port')) self.username = self.get_configuration_for('ftp', 'username') self.password = self.get_configuration_for('ftp', 'password') def setup(self): # An FTP subclass which adds TLS support to FTP self.client = FTP_TLS(timeout=10) def connect(self): self.client.connect(host=self.host, port=self.port) def login(self): self.client.login(user=self.username, passwd=self.password) #Make our connection to the server secure (i.e. encrypted) self.client.prot_p() #This is a hack making 'ftplib' use the EPSV network protocol (i.e. an IPv6 connection) instead of the PASV #protocol (i.e. an IPv4). The reason for doing this is that there is a bug in FTP lib which returns the wrong #IP address after connection to the FTP if PASV is used. In contrast if the EPSV protocol is used the FTP IP is #returned correctly allowing further commands to the FTP connection. self.client.af = socket.AF_INET6 return self.client
def conexionFTP(): print "conexionFTP" global reIntento, rutaFtp,tiempoErr,hostFtp,passFtp,userFtp,portFtp,infoERR #request = urllib.request.Request('http://'+hostFtp) #response = urllib.request.urlopen(request) estatusCftp=False if response.getcode() == 200: try: ftp = FTP_TLS() ftp.connect(hostFtp,portFtp) ftp.login(userFtp, passFtp) ftp.cwd(rutaFtp) estatusCftp = True except Exception as e: if infoERR == True:logger.warning(formErro) logger.warning('Error al conectar al servidor ftp '+str(e)) else: logger.warning('Error al conectar al servidor Error de internet '+str(e)) for i in range(reIntento): if conexionFTP()['ftp']:main() else:logger.warning("reconecion internet intento "+str(i));slp(tiempoErr)# return {'ftp':ftp,'estatusCftp':estatusCftp}
def ftpDownload(filename, system): from ftplib import FTP_TLS import os ftps = FTP_TLS() ftps.connect('pwcrack.init6.me', '21') ftps.auth() ftps.login('DC214', 'passwordcrackingcontest') ftps.prot_p() ftps.set_pasv(True) local_filename = filename with open(local_filename, 'wb') as f: def callback(data): f.write(data) ftps.retrbinary('RETR %s' % filename, callback) f.close() file_extension = str(filename.split('.')[1]) if file_extension == '7z': status = decompressit(local_filename, system) if status: print "file %s hash been downloaded." % local_filename return True
def connect(): ftp = FTP_TLS() ftp.ssl_version = ssl.PROTOCOL_TLSv1_2 ftp.debugging = 2 ftp.connect("localhost", 2121) ftp.login("developer", "password") return ftp
def connexionftp(adresseftp, nom, mdpasse, passif): """connexion au serveur ftp et ouverture de la session - adresseftp: adresse du serveur ftp - nom: nom de l'utilisateur enregistré ('anonymous' par défaut) - mdpasse: mot de passe de l'utilisateur ('anonymous@' par défaut) - passif: active ou désactive le mode passif (True par défaut) retourne la variable 'ftplib.FTP' après connexion et ouverture de session """ try: verbose('Attente connexion FTP .....') if modeSSL: ftp = FTP_TLS() ftp.connect(adresseftp, 21) ftp.login(nom, mdpasse) ftp.prot_p() ftp.set_pasv(passif) else: ftp = (ftplib.FTP(adresseftp, nom, mdpasse)) ftp.cwd(destination) verbose ('Destination : '+destination) verbose('Connexion FTP OK') etat = ftp.getwelcome() verbose("Etat : "+ etat) return ftp except: verbose('Connexion FTP impossible', True) suppressionDossierTemp(dossierTemporaireFTP) sys.exit()
def ftp_connection(): ftp_conn = None try: logger = get_logger() logger.info("Creating object FTP_TLS()") ftp_conn = FTP_TLS() logger.info("Trying to connect to FTP(%s, %d)", FTP_HOST_NAME, FTP_PORT_NUMBER) ftp_conn.connect(FTP_HOST_NAME, FTP_PORT_NUMBER) ftp_conn.auth() logger.info("auth() 0k") ftp_conn.prot_p() logger.info("prot_p() 0k") logger.info("Trying with FTP_USER_NAME = %s", FTP_USER_NAME) ftp_conn.login(user=FTP_USER_NAME, passwd=FTP_ACCESS_KEY) ftp_conn.set_debuglevel(2) logger.info('Connected') except Exception as e: logger.error('Not connected %s', e) return ftp_conn
def connect(self): #初始化 FTP 链接 if self.ftp_ssl: ftp = FTPS() else: ftp = FTP() print('-'*20+self.ftp_name+'-'*20) print('connect '+('ftps' if self.ftp_ssl else 'ftp')+'://'+self.ftp_host+':'+self.ftp_port) try: ftp.connect(self.ftp_host,self.ftp_port) except Exception as e: print (e) print ('connect ftp server failed') sys.exit() try: ftp.login(self.ftp_user,self.ftp_passwd) print ('login ok') except Exception as e:#可能服务器不支持ssl,或者用户名密码不正确 print (e) print ('Username or password are not correct') sys.exit() if self.ftp_ssl: try: ftp.prot_p() except Exception as e: print (e) print ('Make sure the SSL is on ;') print(ftp.getwelcome()) ftp.cwd(self.ftp_webroot) print('current path: '+ftp.pwd()) self.ftp=ftp
def connect(self, context): ui_props = context.scene.editAsset ftp = FTP_TLS() ftp.connect('ftp.luxcorerender.org', 21) ftp.login(ui_props.username, ui_props.password) return ftp
def download_npc(): ftp_files = [] os_files = [] try: ftps = FTP_TLS() ftps.connect(CFG_FTPS_HOST, CFG_FTPS_PORT) log_it( 'connected to ' + CFG_FTPS_HOST + ' welcome message: ' + str(ftps.getwelcome()), 'info') ftps.login(CFG_FTPS_USER, CFG_FTPS_PASS) ftps.prot_p() log_it('changing dir: ' + CFG_FTPS_DIR, 'info') ftps.cwd(CFG_FTPS_DIR) ftp_files = ftps.nlst() for f in ftp_files: if not os.path.isfile(CFG_ARCHIVE_DIR + f): ftps.retrbinary('RETR ' + f, open(CFG_ARCHIVE_DIR + f, 'wb').write) log_it('downloading file ' + f, 'info') else: log_it( 'skipping ' + f + ' as it already exists in ' + CFG_ARCHIVE_DIR, 'debug') except ftplib.all_errors, e: log_it('unable to connect to ' + CFG_FTPS_HOST + ' %s' % e, 'error')
def connect_ftp(): #Connect to the server ftp = FTP_TLS() ftp.connect(SERVER, PORT) ftp.login(USER, PASS) return ftp
def storeFtplib(dataframe, filename="cameliaBalAGKevin.csv", compression = None, toPrint = False): """ function that connects to the remote FTP serveur and upload a pandas dataframe the upload file must be a pandasDataframe and will be written in a csv file. It can be uploaded as a bz2, gz encoded or not encoded at all if it is encoded, the right extension must be present in the name -- IN dataframe : the dataframe to upload (pandas.Dataframe) filename : the filename with its extension to be downloaded from the remote ftp server (string) compression : string that specifies the encoding of the file (string in [None,"gz","bz2"] default: None toPrint : boolean that settles if the function should print its progress and results (boolean) default: False -- OUT flag : boolean that settles if everything was successful (True: no problem, False: an error occured) """ startTime = time.time() if toPrint: print "" print "" print "===========================================" print "=== Connection to the remote FTP server ===" print "===========================================" print "" print "using ftplib" print "loading :",filename print "" ftp = FTP_TLS() # retrieving information about account on ftp server (user, password, host, port) = getAccount() if user==None: print "error : coudn't read the account information" return False # connecting and logging in try: ftp.connect(host,port) ftp.login(user,password) except: print "error : unable to connect to the ftp server" return False # establishing the security protocol ftp.prot_p() if toPrint: print "connected to the FTP server" try: lines = dataframe.to_csv(path_or_buff = None,sep="\t",columns=dataframe.columns) except: print "error : impossible to convert the dataframe into csv lines" return False sio = StringIO.StringIO(lines) ftp.storlines(cmd="STOR "+filename, fp=sio) # try: # ftp.storlines(cmd="STOR "+filename, file=lines) # except: # print "error : impossible to upload the file" # return False interval = time.time() - startTime if toPrint: print 'Dataframe uploaded :', interval, 'sec' return True
def start_ftpes_connection(timeout=30): ftps = FTP_TLS(timeout=timeout) ftps.connect(SETTINGS['exporters.plan2learn.host'], 21) ftps.auth() ftps.prot_p() ftps.login(SETTINGS['exporters.plan2learn.user'], SETTINGS['exporters.plan2learn.password']) return ftps
def ftpconnect(host, port, username, password): from ftplib import FTP_TLS ftps = FTP_TLS(timeout=100) ftps.connect("135.32.1.36", 2121) ftps.auth() ftps.prot_p() ftps.login('ftpuser', 'ftpoptr') return ftp
def whitelistUpdate(self): ftp = FTP_TLS() #ftp.set_debuglevel(2) ftp.connect(os.getenv("FTP_IP"), int(os.getenv("FTP_PORT"))) ftp.login(os.getenv("FTP_LOGIN"), os.getenv("FTP_PASSWORD")) whitelist = open(self.whitelistJSON, 'rb') ftp.storlines('STOR whitelist.json', whitelist) ftp.quit() return
def connect(user, password, ip_address='pensieve.usc.edu', port=41590): ftp = FTP_TLS() ftp.ssl_version = ssl.PROTOCOL_SSLv23 ftp.debugging = 2 ftp.connect(ip_address, port) ftp.login(user, password) ftp.prot_p() ftp.retrlines('LIST home') return(ftp)
def connect(): config = configparser.ConfigParser() config.read('config.ini') ftp = FTP_TLS() ftp.ssl_version = ssl.PROTOCOL_SSLv23 ftp.connect(config['node53']['address'], 21) ftp.login(config['node53']['user'], config['node53']['password']) print(ftp.prot_p()) return ftp
def connect(self): print(f"{self.server} {self.port} {self.usrname} {self.pwd}") ftp = FTP_TLS() try: ftp.connect(self.server, self.port) ftp.login(self.usrname, self.pwd) except: raise IOError('\n FTP login failed!!!') else: print(ftp.getwelcome()) print('\n+------- FTP connection successful!!! --------+\n') return ftp
def ftp_connection(): credentials = get_credentials() ftp = FTP_TLS() ftp.connect(credentials['ftp_client'], ) ftp.login( credentials['user'], credentials['password'], ) server_data = parse_server_data(ftp) ftp.quit()
def openFtpConnection(self, host="localhost", port=21, login="******", password=None, timeout=600, isSecured=False): self.isSecured = isSecured if (isSecured == True): _ftpConnection = FTP_TLS(timeout=timeout) _ftpConnection.connect(host, port) _ftpConnection.auth() _ftpConnection.prot_p() else: _ftpConnection = self.FTP(timeout=timeout) _ftpConnection.connect(host, port) _ftpConnection.login(login, password) self.ftpConnection = _ftpConnection
def upload_xml(): ftps = FTP_TLS(cfg.BING_IP_ADDRESS) ftps.connect() ftps.login(cfg.BING_FTP_USERNAME, cfg.BING_FTP_PASSWORD) ftps.getwelcome() # Add upload code here storbinary() file = open('bing.txt', 'rb') ftps.storbinary('STOR ' + 'bing.txt', file) file.close() ftps.quit()
def conectaFtpPort(): host = os.environ["HOST_FTP"] port = os.environ["PORT_FTP"] user = os.environ["USER_FTP"] pswd = os.environ["PSWD_FTP"] tp = FTP_TLS() tp.connect(host, ast.literal_eval(port), -999) tp.login(user, pswd) tp.prot_p() tp.dir() print(tp)
def ftpUpload(filename): from ftplib import FTP_TLS import os ftps = FTP_TLS() ftps.connect('pwcrack.init6.me', '21') ftps.auth() ftps.login('DC214', 'passwordcrackingcontest') ftps.prot_p() ftps.set_pasv(True) local_file = open(filename, 'rb') ftps.storbinary('STOR '+filename, local_file)
def ftpUpload(filename): from ftplib import FTP_TLS import os ftps = FTP_TLS() ftps.connect('pwcrack.init6.me', '21') ftps.auth() ftps.login('DC214', 'passwordcrackingcontest') ftps.prot_p() ftps.set_pasv(True) local_file = open(filename, 'rb') ftps.storbinary('STOR ' + filename, local_file)
def testFTPS(hostname, username, password, port, path, passive): try: ftp = FTP_TLS() ftp.connect(hostname, port) ftp.login(username, password) ftp.prot_p() ftp.set_pasv(passive) ftp.cwd(path) files = ftp.dir() ftp.quit() return True except BaseException as error: return error
def Push( FtpServer, Username, Password, uploadlist = FilesToPut, port = 21, passive = False, StartTls = False, Sftp = False ): print "Login to %s:%s using %s:%s (%s%s)"%(FtpServer, port, Username, 'xxx', 'passive' if passive else 'active', '/tls' if StartTls else '') if Sftp: paramiko.util.log_to_file('/tmp/paramiko.log') transport = paramiko.Transport((FtpServer,int(port))) transport.connect(username = Username, password = Password) sftp = paramiko.SFTPClient.from_transport(transport) print "Uploading file" filepath = '../php/basedata.php' localpath = 'basedata.php' sftp.put(filepath, localpath) sftp.close() transport.close() else: if StartTls: ftp = FTP_TLS() else: ftp = FTP() ftp.connect( FtpServer, port ) ftp.login( Username, Password) ftp.set_pasv( passive ) if StartTls: ftp.prot_p() for f in uploadlist: print "uploading %s"%f fp = open( f, 'rb') ftp.storbinary('STOR %s'%os.path.basename(f), fp) # send the file ftp.quit() if __name__ == "__main__": if len(sys.argv) < 5: print >> sys.stderr, "usage %s <server> <port> <username> <password>"%sys.argv[0] exit( 1 ) FtpServer = sys.argv[1] Port = sys.argv[2] Username = sys.argv[3] Passwd = sys.argv[4] Push( FtpServer, Username, Passwd, port = Port ) print >> sys.stderr, "Done"
class FTPS: def __init__(self): self.ftps = FTP_TLS( ) def connect(self): self.ftps.connect('192.168.0.102', 2121) print(self.ftps.getwelcome()) def login(self): self.ftps.login('anderson', 'nosredna89') self.ftps.prot_p() #para fazer a conexação de dados segura def close(self): self.ftps.close()
def ftpDownload(filename): from ftplib import FTP_TLS import os ftps = FTP_TLS() ftps.connect('pwcrack.init6.me', '21') ftps.auth() ftps.login('DC214', 'passwordcrackingcontest') ftps.prot_p() ftps.set_pasv(True) local_filename = filename with open(local_filename, 'wb') as f: def callback(data): f.write(data) ftps.retrbinary('RETR %s' % filename, callback)
def Push( FtpServer, Username, Password, uploadlist = FilesToPut, port = 21): print >> sys.stderr, "Login to %s:%s using %s:%s"%(FtpServer, port, Username, 'xxx') ftp = FTP() ftps = FTP_TLS() ftps.connect(FtpServer,Port) ftps.auth() ftps.login(Username, Password) # login anonymously before securing control channel ftps.prot_p() ftp.set_pasv(False) for f in uploadlist: #print "uploading %s"%f fp = open( f, 'rb') os.path.basename(f) print f ftp.storbinary("STOR,%sx " %(os.path.basename(f),fp)) #ftp.storbinary('STOR, %s',fp %(basename(f)) ) # send the file ftp.quit()
def ftp_backup(dmpdir,dbname): try: # ftp =FTP_TLS() ftp.connect(ftphost,ftpport) ftp.login(ftpuser,ftppass) ftp.prot_p() print "Welcome:",ftp.getwelcome() print ftp.retrlines('LIST') # ftp =FTP() # ftp.connect(ftphost,ftpport) # ftp.login(ftpuser,ftppass) # print "Welcome:",ftp.getwelcome() # print ftp.retrlines('LIST') except Exception,e: print e return
def getfiles(server, port, user, password, db): sqliteconnection = sqlite3.connect(db) sqlitecursor = sqliteconnection.cursor() sqlitecursor.execute('''CREATE TABLE IF NOT EXISTS latest (date int, CONSTRAINT 'id_UNIQUE' UNIQUE ('date'))''') sqliteconnection.commit() sqlitecursor.execute('''SELECT date FROM files WHERE date = (SELECT MAX(date) FROM files) LIMIT 1''') latestfile = sqlitecursor.fetchone() sqlitecursor.execute('''SELECT date FROM latest WHERE date = (SELECT MAX(date) FROM latest) LIMIT 1''') latestfetch = sqlitecursor.fetchone() if latestfetch is None: latestfetch = 0 if latestfetch < latestfile: ftpsconnection = FTP_TLS() ftpsconnection.connect(server, port) ftpsconnection.auth() ftpsconnection.prot_p() ftpsconnection.login(user, password) ftpsconnection.prot_p() sqlitecursor.execute('''SELECT name FROM files WHERE date > %d''' % latestfetch) filestofetch = sqlitecursor.fetchall() for currfile in filestofetch: ftpsconnection.cwd(currfile[0]) filenames = ftpsconnection.nlst() for filename in filenames: print 'Now saving /mnt/folder' + currfile[0] + '/' + filename localfile = open('/mnt/folder' + currfile + '/' + filename, 'wb') ftpsconnection.retrbinary('RETR ' + filename, localfile.write) localfile.close() sqliteconnection.execute('''INSERT OR IGNORE INTO latest VALUES (%d)''' % time.time()) sqliteconnection.commit() sqliteconnection.close() ftpsconnection.quit() ftpsconnection.close()
def ftpUpload(filename, system): from ftplib import FTP_TLS import os if os.path.isfile(filename): zipFilename = compressit(filename, system) ftps = FTP_TLS() ftps.connect('pwcrack.init6.me', '21') ftps.auth() ftps.login('DC214', 'passwordcrackingcontest') ftps.prot_p() ftps.set_pasv(True) local_file = open(zipFilename, 'rb') ftps.storbinary('STOR '+zipFilename, local_file) print "file %s has been uploaded." % zipFilename return True
def make_msg(self, args): # make connection conn = None if args.ssl or args.starttls: conn = FTP_TLS() conn.ssl_version = PROTOCOL_TLSv1 else: conn = FTP() if args.verbose: conn.set_debuglevel(1) conn.connect(args.host, args.port, args.timeout) if args.starttls: conn.auth() conn.prot_p() conn.login(args.user, args.password) self.conn = conn return args.message
def ftpDownload(filename, system): from ftplib import FTP_TLS import os ftps = FTP_TLS() ftps.connect('pwcrack.init6.me', '21') ftps.auth() ftps.login('DC214', 'passwordcrackingcontest') ftps.prot_p() ftps.set_pasv(True) local_filename = filename with open(local_filename, 'wb') as f: def callback(data): print "Downloading %s ..." % filename f.write(data) ftps.retrbinary('RETR %s' % filename, callback) f.close() file_extension = str(filename.rsplit('.')[2]) if file_extension == '7z': status = decompressit(local_filename, system) if status: print "file %s has been downloaded." % local_filename
def testFTPLibConnection(self): ''' tests if the ftplib connection is available with the FTP server ''' ftp = FTP_TLS() (user, password, host, port) = getAccount() ftp.connect(host,port) ftp.login(user,password)
import sys,json server = json.loads(sys.argv[1]) try: if server['secure'] == True: from ftplib import FTP_TLS ftp = FTP_TLS() else: from ftplib import FTP ftp = FTP() ftp.connect(server['host'], server['port']) ftp.login(server['user'], server['pass']) ftp.delete(sys.argv[2]) ftp.quit() except: sys.exit(1)
class FTPES: def __init__(self, host, port=None, username=None, password=None, remote_path=None, absolute_zipfile_path=None): """ This is a helper class to manage the FTP commands from the ftplib. @param host: The host for the connection. @type host: String @param port: The post for the connection. @type port: Integer @param username: The username for the connection. Leave blank to use "anonymous". @type username: String @param password: The password for the connection. Leave empty for none. @type password: String @param remote_path: The remote path of the server in which the zip file should be uploaded. If the path does not exists, it will be created (recursive). @type remote_path: String @param absolute_zipfile_path: The absolute LOCAL filepath of the zip file. @type absolute_zipfile_path: String """ self.ftps = None self._host = host self._port = port self._username = username self._password = password self._remote_path = remote_path self._absolute_zipfile_path = absolute_zipfile_path self._bytesWritten = 0; self._totalFileSize = os.path.getsize(self._absolute_zipfile_path) self._uploadCallback = None self._currentProgress = 0 # make the remote path relative if it isnt absolute or relative yet if self._remote_path is not None and self._remote_path.startswith( '.') is False and self._remote_path.startswith('/') is False: self._remote_path = './' + self._remote_path if self._username is None: self._username = '******' if self._port is None: self._port = 22 def connect(self): """ Try to connect to the FTP server. Raise an error if something went wrong. """ try: self.ftps = FTP_TLS() self.ftps.set_pasv(True) self.ftps.connect(self._host, self._port) except socket.gaierror: raise def login(self): """ Try to login in on the FTP server. Raise an error if something went wrong. """ try: self.ftps.login(self._username, self._password) self.ftps.prot_p() except ftplib.error_perm: raise def cwd(self): """ Try to switch the working directory on the FTP server (if set in the settings). If the path does not exist, it will be created. """ if self._remote_path is not None: try: self.ftps.cwd(self._remote_path) except ftplib.error_perm: self.create_directory_tree(self._remote_path) except IOError: raise def create_directory_tree(self, current_directory): """ Helper function to create the remote path. @param current_directory: The current working directory. @type current_directory: String """ if current_directory is not "": try: self.ftps.cwd(current_directory) except ftplib.error_perm: self.create_directory_tree("/".join(current_directory.split("/")[:-1])) self.ftps.mkd(current_directory) self.ftps.cwd(current_directory) except IOError: raise def upload(self, callback=None): """ The upload function. @param callback: The callback function for the upload progress. @type callback: Function """ self._uploadCallback = callback zipfile_to_upload = open(self._absolute_zipfile_path, 'rb') zipfile_basename = os.path.basename(self._absolute_zipfile_path) self.ftps.storbinary('STOR %s' % zipfile_basename, zipfile_to_upload, 1024, self.handle_upload_state) zipfile_to_upload.close() def handle_upload_state(self, block): """ The callback function for the upload progress. @param block: The StringIO of the current upload state @type block: StringIO """ self._bytesWritten += 1024 progress = math.floor((float(self._bytesWritten) / float(self._totalFileSize)) * 100) do_update = False if progress > self._currentProgress: do_update = True self._currentProgress = progress if self._uploadCallback is not None: self._uploadCallback(progress, self, do_update) def quit(self): """ Try to quit everything and close the session. """ self.ftps.quit() @property def upload_path(self): """ Returns the upload path of the FTP server. @return: The path of the uploaded file on the FTP server. @rtype: String """ tmp_remote_path = '' if self._remote_path is not None: tmp_remote_path = self._remote_path return os.path.join(tmp_remote_path, os.path.basename(self._absolute_zipfile_path))
# version one: # may, 05, 2016 # so, super simple thing to log into an ftp, and issue the command you pass # in the argument # syntax: ./script <command> # the idea is to run this from an eggdrop as a trigger, no fluff from ftplib import FTP_TLS from sys import argv filename, argument = argv ftps = FTP_TLS() #ftps.set_debuglevel(2) # if you broke something, uncomment this (run it directly, not from eggdrop) ftps.connect('your.host', '1111') # enter your server and port within the quotes ftps.login('specialftpuser', 'qwerty') # enter your user and pass within the quotes (remember, not a user with privs) ftps.prot_p() ftps.sendcmd('site ' + argument) # the tcl script i included will take any output from this python and spam # it into the channel.. set this how you like, or turn it off # if you're a tcl guru comment this out and make your tcl do the accounce print "cmd sent, sleeping now zzzz" ftps.quit() quit()
class FTPClient(object): """Class FTPClient """ _mh = None _client = None _secured = None _host = None _port = None _user = None _passw = None _path = None _verbose = None _is_connected = None def __init__(self, secured=False, verbose=False): """Class constructor Called when the object is initialized Args: secured (bool): secured FTP verbose (bool): verbose mode """ self._mh = MasterHead.get_head() self._secured = secured if (not self._secured): self._client = FTP() else: if (not(version_info[0] == 2 and version_info[1] == 6)): self._client = FTP_TLS() else: raise NotImplementedError( 'Secured mode is not supported for Python 2.6') self._verbose = verbose if (self._verbose): self._client.set_debuglevel(2) @property def client(self): """ FTP client property getter """ return self._client @property def secured(self): """ secured protocol mode property getter """ return self._secured @property def host(self): """ server host property getter """ return self._host @property def port(self): """ server port property getter """ return self._port @property def user(self): """ username property getter """ return self._user @property def passw(self): """ user password property getter """ return self._passw @property def path(self): """ remote path property getter """ return self._path @property def verbose(self): """ verbose mode property getter """ return self._verbose @property def is_connected(self): """ is_connected property getter """ return self._is_connected def connect(self, host, port=21, user=None, passw=None, path='/', timeout=10): """Method connects to server Args: host (str): server host port (int): server port, default protocol port user (str): username passw (str): password path (str): server path timeout (int): timeout Returns: bool: result Raises: event: ftp_before_connect event: ftp_after_connect """ try: message = '{0}/{1}@{2}:{3}{4} timeout:{5}'.format( user, passw, host, port, path, timeout) self._mh.demsg('htk_on_debug_info', self._mh._trn.msg( 'htk_ftp_connecting', message), self._mh.fromhere()) ev = event.Event( 'ftp_before_connect', host, port, user, passw, path, timeout) if (self._mh.fire_event(ev) > 0): host = ev.argv(0) port = ev.argv(1) user = ev.argv(2) passw = ev.argv(3) path = ev.argv(4) timeout = ev.argv(5) self._host = host self._port = port self._user = user self._passw = passw if (ev.will_run_default()): self._client.connect(self._host, self._port, timeout=timeout) if (self._user != None): self._client.login(self._user, self._passw) if (self._secured): self._client.prot_p() self._is_connected = True self._mh.demsg('htk_on_debug_info', self._mh._trn.msg( 'htk_ftp_connected'), self._mh.fromhere()) if (path != None): self.change_dir(path) ev = event.Event('ftp_after_connect') self._mh.fire_event(ev) return True except all_errors as ex: self._mh.demsg( 'htk_on_error', 'error: {0}'.format(ex), self._mh.fromhere()) return False def disconnect(self): """Method disconnects from server Args: none Returns: bool: result """ try: if (not self._is_connected): self._mh.demsg('htk_on_warning', self._mh._trn.msg( 'htk_ftp_not_connected'), self._mh.fromhere()) return False else: self._client.quit() self._is_connected = False self._mh.demsg('htk_on_debug_info', self._mh._trn.msg( 'htk_ftp_disconnected'), self._mh.fromhere()) return True except all_errors as ex: self._mh.demsg( 'htk_on_error', 'error: {0}'.format(ex), self._mh.fromhere()) return False def list_dir(self): """Method lists remote working directory Args: none Returns: list: names """ try: self._mh.demsg('htk_on_debug_info', self._mh._trn.msg( 'htk_ftp_list_dir', self._path), self._mh.fromhere()) if (not self._is_connected): self._mh.demsg('htk_on_warning', self._mh._trn.msg( 'htk_ftp_not_connected'), self._mh.fromhere()) return False names = self._client.nlst() if ('.' in names): names.remove('.') if ('..' in names): names.remove('..') return names except all_errors as ex: self._mh.demsg( 'htk_on_error', 'error: {0}'.format(ex), self._mh.fromhere()) return None def change_dir(self, path): """Method changes remote working directory Args: path (str): new remote path Returns: bool: result Raises: event: ftp_before_change_dir """ try: self._mh.demsg('htk_on_debug_info', self._mh._trn.msg( 'htk_ftp_change_dir', path), self._mh.fromhere()) if (not self._is_connected): self._mh.demsg('htk_on_warning', self._mh._trn.msg( 'htk_ftp_not_connected'), self._mh.fromhere()) return False ev = event.Event('ftp_before_change_dir', path) if (self._mh.fire_event(ev) > 0): path = ev.argv(0) if (ev.will_run_default()): self._client.cwd(path) self._path = self._client.pwd() self._mh.demsg('htk_on_debug_info', self._mh._trn.msg( 'htk_ftp_cur_dir', self._path), self._mh.fromhere()) return True except all_errors as ex: self._mh.demsg( 'htk_on_error', 'error: {0}'.format(ex), self._mh.fromhere()) return False def download_file(self, remote_path, local_path=None): """Method downloads file from server Args: remote_path (str): remote path local_path (str): local path, default ./filename Returns: bool: result Raises: event: ftp_before_download_file event: ftp_after_download_file """ try: self._mh.demsg('htk_on_debug_info', self._mh._trn.msg( 'htk_ftp_downloading_file', remote_path), self._mh.fromhere()) if (not self._is_connected): self._mh.demsg('htk_on_warning', self._mh._trn.msg( 'htk_ftp_not_connected'), self._mh.fromhere()) return False ev = event.Event( 'ftp_before_download_file', remote_path, local_path) if (self._mh.fire_event(ev) > 0): remote_path = ev.argv(0) local_path = ev.argv(1) if (local_path != None and not path.exists(local_path)): self._mh.demsg('htk_on_error', self._mh._trn.msg( 'htk_ftp_unknown_dir', local_path), self._mh.fromhere()) return False filename = remote_path.split('/')[-1] lpath = filename if (local_path == None) else path.join( local_path, filename) if (ev.will_run_default()): with open(lpath, 'wb') as f: self._client.retrbinary('RETR ' + remote_path, f.write) self._mh.demsg('htk_on_debug_info', self._mh._trn.msg( 'htk_ftp_file_downloaded'), self._mh.fromhere()) ev = event.Event('ftp_after_download_file') self._mh.fire_event(ev) return True except all_errors as ex: self._mh.demsg( 'htk_on_error', 'error: {0}'.format(ex), self._mh.fromhere()) if (path.exists(lpath)): remove(lpath) return False def upload_file(self, local_path, remote_path=None): """Method uploads file to server Args: local_path (str): local path remote_path (str): remote path, default ./filename Returns: bool: result Raises: event: ftp_before_upload_file event: ftp_after_upload_file """ try: self._mh.demsg('htk_on_debug_info', self._mh._trn.msg( 'htk_ftp_uploading_file', local_path), self._mh.fromhere()) if (not self._is_connected): self._mh.demsg('htk_on_warning', self._mh._trn.msg( 'htk_ftp_not_connected'), self._mh.fromhere()) return False ev = event.Event('ftp_before_upload_file', local_path, remote_path) if (self._mh.fire_event(ev) > 0): local_path = ev.argv(0) remote_path = ev.argv(1) if (not(path.exists(local_path) or path.exists(path.relpath(local_path)))): self._mh.demsg('htk_on_error', self._mh._trn.msg( 'htk_ftp_unknown_file', local_path), self._mh.fromhere()) return False filename = local_path.split('/')[-1] rpath = filename if (remote_path == None) else path.join( remote_path, filename) if (ev.will_run_default()): with open(local_path, 'rb') as f: self._client.storbinary('STOR ' + rpath, f) self._mh.demsg('htk_on_debug_info', self._mh._trn.msg( 'htk_ftp_file_uploaded'), self._mh.fromhere()) ev = event.Event('ftp_after_upload_file') self._mh.fire_event(ev) return True except all_errors as ex: self._mh.demsg( 'htk_on_error', 'error: {0}'.format(ex), self._mh.fromhere()) return False def delete_file(self, path): """Method deletes file from server Args: path (str): remote path Returns: bool: result Raises: event: ftp_before_delete_file """ try: self._mh.demsg('htk_on_debug_info', self._mh._trn.msg( 'htk_ftp_deleting_file', path), self._mh.fromhere()) if (not self._is_connected): self._mh.demsg('htk_on_warning', self._mh._trn.msg( 'htk_ftp_not_connected'), self._mh.fromhere()) return False ev = event.Event('ftp_before_delete_file', path) if (self._mh.fire_event(ev) > 0): path = ev.argv(0) if (ev.will_run_default()): self._client.delete(path) self._mh.demsg('htk_on_debug_info', self._mh._trn.msg( 'htk_ftp_file_deleted'), self._mh.fromhere()) return True except all_errors as ex: self._mh.demsg( 'htk_on_error', 'error: {0}'.format(ex), self._mh.fromhere()) return False def make_dir(self, path): """Method makes directory on server Args: path (str): remote path Returns: bool: result Raises: event: ftp_before_make_dir """ try: self._mh.demsg('htk_on_debug_info', self._mh._trn.msg( 'htk_ftp_making_dir', path), self._mh.fromhere()) if (not self._is_connected): self._mh.demsg('htk_on_warning', self._mh._trn.msg( 'htk_ftp_not_connected'), self._mh.fromhere()) return False ev = event.Event('ftp_before_make_dir', path) if (self._mh.fire_event(ev) > 0): path = ev.argv(0) if (ev.will_run_default()): self._client.mkd(path) self._mh.demsg('htk_on_debug_info', self._mh._trn.msg( 'htk_ftp_dir_made'), self._mh.fromhere()) return True except all_errors as ex: self._mh.demsg( 'htk_on_error', 'error: {0}'.format(ex), self._mh.fromhere()) return False def remove_dir(self, path): """Method removes directory from server Args: path (str): remote path Returns: bool: result Raises: event: ftp_before_remove_dir """ try: self._mh.demsg('htk_on_debug_info', self._mh._trn.msg( 'htk_ftp_removing_dir', path), self._mh.fromhere()) if (not self._is_connected): self._mh.demsg('htk_on_warning', self._mh._trn.msg( 'htk_ftp_not_connected'), self._mh.fromhere()) return False ev = event.Event('ftp_before_remove_dir', path) if (self._mh.fire_event(ev) > 0): path = ev.argv(0) if (ev.will_run_default()): self._client.rmd(path) self._mh.demsg('htk_on_debug_info', self._mh._trn.msg( 'htk_ftp_dir_removed'), self._mh.fromhere()) return True except all_errors as ex: self._mh.demsg( 'htk_on_error', 'error: {0}'.format(ex), self._mh.fromhere()) return False
def retrieveFtplib(filename, compression = None, usecols=None, dtype=None, toPrint = False, sep="\t"): """ function that connects to the remote FTP serveur and extract a pandas dataframe the downloaded file must contain a csv file. It can be bz2, gz encoded or not encoded at all if it is encoded, the right extension must be present in the name -- IN filename : the filename with its extension to be downloaded from the remote ftp server (string) compression : string that specifies the encoding of the file (string in [None,"gz","bz2"] default: None usecols : an array containing the name of the column to extract (string[]) default: None dtype : a dictionary containing the name of the columns and the type to cast them ({string:string}) default: None toPrint : boolean that settles if the function should print its progress and results (boolean) default: False -- OUT db : a pandas dataframe containing the remote database (pandas.Dataframe) return None when an error occurs """ startTime = time.time() if toPrint: print "===========================================" print "=== Connection to the remote FTP server ===" print "===========================================" print "" print "using ftplib" print "loading :",filename print "" ftp = FTP_TLS() # retrieving information about account on ftp server (user, password, host, port) = getAccount() if user==None: print "error : coudn't read the account information" return None # connecting and logging in try: ftp.connect(host,port) ftp.login(user,password) except: print "error : unable to connect to the ftp server" return None # establishing the security protocol ftp.prot_p() if toPrint: print "connected to the FTP server" # retrieving the remote file as a binary file sio = StringIO.StringIO() def handle_binary(more_data): sio.write(more_data) try: ftp.retrbinary("RETR "+filename, callback=handle_binary) except: print "error : non-existing file :",filename return None # Go back to the start of the binary file sio.seek(0) interval = time.time() - startTime if toPrint: print 'Data downloaded :', interval, 'sec' # Unziping the file if compression!=None: if compression=="gz": try: results = gzip.GzipFile(fileobj=sio) except: print "error : decompression impossible : not a gzip file" return None if toPrint: interval = time.time() - startTime print 'Decompression done :', interval, 'sec' elif compression=="bz2": results = StringIO.StringIO() a = bz2.decompress(sio.read()) results.write(a) results.seek(0) try: pass except: print "error : decompression impossible : not a bz2 file" return None if toPrint: interval = time.time() - startTime print 'Decompression done :', interval, 'sec' else: results = sio # extracting the file into a pandas dataframe try: db = pd.read_csv(results,sep=sep, usecols = usecols) except: print "error : the file doesn't not contain a proper Dataframe" return None sio.close() interval = time.time() - startTime if toPrint: print 'Dataframe created :', interval, 'sec' return db
from ftplib import FTP_TLS ftps = FTP_TLS() ftps.connect('127.0.0.1', 5000) ftps.login('user', '12345') # login anonymously before securing control channel ftps.prot_p() # switch to secure data connection ftps.retrlines('LIST') # list directory content securely
createEmptyDirectory = True if opt == "-l": detectLink = True if ':' in args[0]: host, port = args[0].split(':') else: host, port = args[0], "21" #convert port as int port = int(port) if enableSSL: if port == 21: client = FTP_TLS(host) client.auth() client.prot_p() else: client = FTP_TLS_EXPLICIT() client.connect(host, port) client.prot_p() else: client = FTP() print client.connect(host, int(port)) print client.login(username, password) #log client.login(username, password) Dumper(client, createEmptyDirectory, filter, detectLink).do(targetDir) client.quit()