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 get_txtfile(): ftps = FTP_TLS("ftps.cookcountyclerk.com") ftps.login(user='******', passwd='R3p047') ftps.prot_p() ftps.getwelcome() ftps.dir() print('getting new txt file') with open( 'scrapers/cook_files/updated_cook.txt', 'wb' ) as new_results: # this should create a new file called updated_cook.txt ftps.retrbinary( 'RETR ' + 'SummaryExport.txt', new_results.write ) # confirm the name of the file that will have updated results print('exiting server') ftps.quit()
def main(): ftp = FTP_TLS() ftp.connect(host = FTP_SERVER_HOST) ftp.login(user=USERNAME, passwd=PASSWORD) ftp.dir() ftp.cwd('/ebipmft-concurintelligenceextract-vd') ftp.dir() print(ftp.getwelcome()) file_remote = r'otpo.csv' file_local = r'C:\users\eweitia\desktop\otpo.csv' bufsize = 1024 # 设置缓冲器大小 fp = open(file_local, 'wb') ftp.retrbinary('RETR %s' % file_remote, fp.write, bufsize) ftp.quit() ftp.close()
def cliente_ftp_conexion(servidor, nombre_usuario, password): #abrimos la conexion ftps = FTP_TLS(servidor) ftps.login(nombre_usuario, password) #ftp = ftplib.FTP(servidor, nombre_usuario, password) #listamos los archivos de / ftps.cwd("/") print "Archivos disponibles en %s:" % servidor archivos = ftps.dir() print archivos ftps.quit()
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
class FtpHelper: def __init__(self, host, port, user, password): self.ftp = FTP_TLS() self.ftp.connect(host=host, port=int(port)) self.ftp.login(user=user, passwd=password) self.ftp.prot_p() def list_files(self, path=None): """ Lister les fichiers présents dans un dossier Parameters ---------- path: Path vers le dossier Return Liste des fichier présents dans le dossier ------- """ if Config.get_secret('WORKING_ENV') == 'LOCAL': return [file for file in os.listdir(Config.get_secret('ZIP_FILES_PATH'))] files = [] if path is not None: self.ftp.cwd(path) self.ftp.dir(files.append) return [filename.split(' ')[-1] for filename in files]
def linkFtp(folder=''): """ Handlser FTP per il caricamento dei dati su server remoto :param folder: sotto cartella di salvataggio remota :return: handler per la gestione """ # ftp = FTP_TLS() ftp = FTP_TLS(host=rl['host']) ftp.set_debuglevel(2) status = ftp.login(user=rl['username'], passwd=rl['password']) # comando per il cambio della directory di upload ftp.cwd(backup_folder+'/'+folder) # print the content of directory print(ftp.dir()) return ftp, status
def shell(host, port, user, passwd, use_ftps): """ Shell Mode function. Provides a CLI to interact with FTP server """ """ Args: host address, port number to connect, user[name] and passw[or]d to login, """ """ use_ftps - if true use FTPS instead of FTP """ #preparation: connect to the server try: if (use_ftps == "y"): if (user != ""): #if username defined ---> use it if (port == "def" or port == ""): #use default port 21 ftps = FTP_TLS(host=host, user=user, passwd=passwd) else: ftps = FTP_TLS(host=host, user=user, passwd=passwd, acct=port) else: #anon login if (port == "def" or port == ""): #use default port 21 ftps = FTP_TLS(host=host) ftps.login() else: ftps = FTP_TLS(host=host, acct=port, user=user, passwd=str(passwd)) ftps.login() print("Connecting to host '{0}' through port '{1}'... ".format(host, port)) os.system("echo Entering Shell Mode in 2 seconds") os.system("sleep 2") os.system("clear") print("Server response:\n" + ftp.getwelcome()) if (use_ftps == "n"): if (user != ""): #if username defined ---> use it if (port == "def" or port == ""): #use default port 21 ftp = FTP(host=host, user=user, passwd=passwd) else: ftp = FTP(host=host, user=user, passwd=passwd, acct=port) else: #anon login if (port == "def" or port == ""): #use default port 21 ftp = FTP(host=host) ftp.login() else: ftp = FTP(host=host, acct=port, user=user, passwd=str(passwd)) ftp.login() print("Connecting to host '{0}' through port '{1}'... ".format(host, port)) os.system("echo Entering Shell Mode in 2 seconds") os.system("sleep 2") os.system("clear") print("Server response:\n" + ftp.getwelcome()) except ftplib.all_errors as ex: print(color.red + "An error occured while login: {0}".format(ex) + color.std) return #enter shell mode while(1): try: if (use_ftps == "n"): cmd = input("ftp@{0}~#".format(host)) cmd, arg = parse(cmd) if (cmd == "cd"): ftp.cwd(arg) elif (cmd == "exit"): ftp.quit() return elif (cmd == "ls"): #unix's LS without flags support print(ftp.dir()) elif (cmd == "cmd"): #send a command to the server ftp.sendcmd(arg) elif (cmd == "getbin"): #download file in binary mode ftp.retrbinary(arg) elif (cmd == "gettxt"): #download file on text mode ftp.retrlines(arg) elif (cmd == "unknown"): print("Unknown command.") else: #FTPS cmd = input("ftps@{0}~#".format(host)) cmd, arg = parse(cmd) if (cmd == "cd"): ftps.cwd(arg) elif (cmd == "exit"): ftps.quit() return elif (cmd == "ls"): #unix's LS without flags support print(ftps.dir()) elif (cmd == "cmd"): #send a command to the server ftps.sendcmd(arg) elif (cmd == "getbin"): #download file in binary mode ftps.retrbinary(arg) elif (cmd == "gettxt"): #download file on text mode ftps.retrlines(arg) elif (cmd == "unknown"): print("Unknown command.") except ftplib.all_errors as ex: print(color.red + "Shell mode error: {0}".format(ex) + color.std)
from ftplib import FTP_TLS import os ftps = FTP_TLS(timeout=100) ftps.set_debuglevel(1) ftps.connect("192.168.1.35", 21) ftps.auth() ftps.prot_p() ftps.login('pan', '1') print(ftps.getwelcome()) print(ftps.pwd()) ftps.dir() # 下载文件 os.chdir(r'D:\Desktop\FTP_TLS\FTP\00临时存储') ftps.cwd('/') ftps.nlst() # 获取目录下的文件 filename = 'vsftpd.key' file_handle = open(filename, "wb").write ftps.retrbinary('RETR %s' % os.path.basename(filename), file_handle, blocksize=1024) # 下载ftp文件 # 上传到服务器 bufsize = 1024 localpath = 'D:\\Desktop\\FTP_TLS\FTP\\00临时存储\\test.txt' remotepath = '/test.txt' fp = open(localpath, 'rb') ftps.storbinary('STOR ' + remotepath, fp, bufsize) # 打印证书 print(ftps.context) print(ftps.certfile)
LOG_MAIN.error("OS ERROR : " + str(OSError)) LOG_MAIN.error("OR OS IOError: " + str(IOError)) if __autopilot__.upper() == 'TRUE': # region ftp_connection try: FTP_TLS.port = int(V_FTPS_PORT) ftp_conn = FTP_TLS(V_FTPS_SERVER) ftp_conn.login(V_FTPS_USER, V_FTPS_PASS) ftp_conn.prot_p() if ftp_conn: ftps_chdir(ftp_conn, V_FTPS_RMT_DIR) ftp_conn.retrlines('LIST') data = [] ftp_conn.dir(data.append) coln = [] for line in data: col = line.split() coln.append(col[-1]) # print(get_lasted_file_name_glob(coln)) lastFile = get_lasted_file_name_glob(coln) ftps_download(ftp_conn, lastFile, __dlftpsfiles__, V_FTPS_RMT_DIR) __pathlastfile__ = __dlftpsfiles__ + lastFile try: fullPathBadFile = __pathBADFILE__ + os.path.splitext( lastFile)[0] fullPathDSCFile = __pathDSCFILE__ + os.path.splitext(
class FtpService: def __init__(self, config: FtpConfiguration): self.config = config self.__connect() def __connect(self) -> None: if self.config.protocol == "FTP": self.ftp = FTP() elif self.config.protocol == "SFTP": self.ftp = FTP_TLS() else: raise UnknownFtpProtocolException(self.config.protocol) self.ftp.connect(host=self.config.host, port=self.config.port, timeout=10) resp: str = self.ftp.login(self.config.username, self.config.passwd) if resp.startswith("230"): logger.info("Successfully connect to FTP server") else: raise CannotConnectToFtpException(self.config) def read_file_items(self, path: str) -> List[FileItem]: files = list() items = list() self.ftp.cwd(path) self.ftp.dir(items.append) for item in items: name, is_file, size = self.__parse_list_line(item) if is_file: file_path = path + "/" + name mdt = self.ftp.sendcmd("MDTM " + file_path) dt = self.__parse_mdt(mdt) files.append(FileItem(file_path, dt, int(size))) return files def download_file(self, ftp_path: str, store_path: str) -> FileItem: a_store_path = pth.abspath(store_path) logger.info("Try download file from ftp \"%s\" to \"%s\"" % (ftp_path, a_store_path)) try: self.ftp.retrbinary("RETR " + ftp_path, open(a_store_path, 'wb').write) except Exception as ex: logger.error("Cannot download file", ex) raise ex return FileSystemHelper.read_file_item(a_store_path) def close(self): self.ftp.close() logger.info("Close ftp connection with server") @staticmethod def __parse_list_line(line: str) -> tuple: items = line.split() is_file = True if items[0].startswith("d"): is_file = False size = items[4] name = items[8:] return str.join(" ", name), is_file, size @staticmethod def __parse_mdt(mdt: str) -> datetime: items = mdt.split() dt = items[1] year = int(dt[0:4]) month = int(dt[4:6]) day = int(dt[6:8]) hour = int(dt[8:10]) minute = int(dt[10:12]) second = int(dt[12:14]) return datetime(year, month, day, hour, minute, second)