python3 ftplib模块连接FTP
from ftplib import FTP_TLS import os import re class MyFtp(FTP_TLS): """继承FTP类""" def dirs(self, *args): """my dirs""" self.encoding = 'GB18030' cmd = 'LIST' if args[-1:] and not isinstance(args[-1], str): args, func = args[:-1], args[-1] for arg in args: if arg: cmd = cmd + (' ' + arg) files = [] self.retrlines(cmd, files.append) l_files = [file.split(" ")[-1] for file in files] return [file for file in l_files if file != "." and file != ".."] ftps = MyFtp() # ftps.set_debuglevel(2) ftps.connect("172.25.22.1",21) #FTP服务IP和端口 ftps.login("user","123456") #FTP用户密码 ftps.prot_p() #继承了MyFtp类中的prot_p方法,目的是为了解决某些开启了安全SSL/TSL而连接不上的问题 ftps.set_pasv(1) #pasv(1)为被动模式,pasv(0为主动模式) ftps.encoding = 'GB18030' #防止中文乱码 ftps.retrlines('LIST') # a = ftps.dirs("/") # print(a) ftps.close()
也可以用更简单的方法:
1 2 3 4 5 6 7 8 9 10 | import os import re import ftplib ftps = ftplib.FTP_TLS() ftps.connect( "172.25.22.1" , 21 ) ftps.login( "user" , "123456" ) ftps.prot_p() ftps.encoding = "GB18030" ftps.retrlines( 'LIST' ) ftps.close() |
取出路径下的文件名
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | import os import re import ftplib ftps = ftplib.FTP_TLS() ftps.connect( "172.25.22.1" , 21 ) ftps.login( "user" , "123456" ) ftps.prot_p() ftps.encoding = "GB18030" ftps.retrlines( 'LIST' ) ftps.close() f1 = [] for file in files: a = re.split( "[ ]+" , file ) f1.append( ' ' .join(a[ 8 :])) print (f1) ftps.close() |
本文作者:香菜哥哥
本文链接:https://www.cnblogs.com/yizhipanghu/p/14261997.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
2019-01-11 Centos 6.5 启动报错 "Kernel panic - not syncing: Attempted to kill init"解决办法