python本身自带一个FTP模块,可以轻松实现FTP的上传,下载等操作。下面来看看用法:
from ftplib import FTP import socket #用来设置超时时间 FTP.connect(服务器地址,端口,超时时间) # 连接服务器 FTP.login(用户名,用户密码) # 用户登录 FTP.pwd(路径) # 读取操作路径 FTP.cwd(路径) # 设置要操作FTP文件夹路径 FTP.nlst() # 获得目录下文件 FTP.retrbinary(文件名, 回调函数) # 下载FTP上的文件 FTP.delete(文件名) # 删除FTP文件 FTP.storbinary(文件名, 文件对象 [,块大小]) # 上传FTP文件 FTP.quit() # 退出FTP服务器 FTP.set_pasv(boolean) # 是否设置为被动模式 FTP.rename(old, new) # 重命名 FTP.delete(path) # 删除文件 FTP.mkd(directory) # 创建目录 |
一个上传代码:
import socket from ftplib import FTP ftp_server='xx.xx.xx.xx' ftp_user='xxxxx' ftp_password='xxxxx' ftp_backup_dir='backup' newday = date.today() #获取今天的日期 oldday = date.today()-timedelta(5) #获得5天前的日期 newfile = '/home/backup/' + 'backup_data_' + str(newday.year) + '.' + str(newday.month) + '.' + str(newday.day) + '.zip' #本次备份文件名(绝对路径) oldfile = '/home/backup/' + 'backup_data_' + str(oldday.year) + '.' + str(oldday.month) + '.' + str(oldday.day) + '.zip' #5天前备份的文件名(绝对路径) def upload(): socket.setdefaulttimeout(60) #超时FTP时间设置为60秒 ftp = FTP(ftp_server) print("login ftp...") try: ftp.login(ftp_user, ftp_password) print(ftp.getwelcome()) #获得欢迎信息 try: if ftp_backup_dir in ftp.nlst(): print("found backup folder in ftp server, upload processing.") else: print("don't found backup folder in ftp server, try to build it.") ftp.mkd(ftp_backup_dir) except: print("the folder" + ftp_backup_dir + "doesn't exits and can't be create!") sys.exit() except: print("ftp login failed.exit.") sys.exit() ftp.cwd(ftp_backup_dir) #设置FTP路径 print("upload data...") try: ftp.storbinary('STOR ' + os.path.basename(newfile), open(newfile,'rb'), 1024) #上传备份文件 except: print("upload failed. check your permission.") print("delte old file...") try: ftp.delete(os.path.basename(oldfile)) #删除5天前的备份文件 except: print("the old file in ftp doesn't exists, jumped.") print("ftp upload successful.exit...") ftp.quit() if __name__== '__main__': upload() |
示例2:
ftpserver = "192.168.0.1"
# 建立FTP连接
ftp = ftplib.FTP(ftpserver)
# FTP用户验证
ftp.login('administrator', 'sunfast')
# 切换ftp操作目录
ftp.cwd("/fromcovisint/094200005560743089CHN03_830")
for filename in ftp.nlst(): # 获取ftp操作目录的所有文件
if os.path.splitext(filename)[1].upper() == '.CSV':
if 'FINISHED' in filename:
continue
else:
try:
#下载指定文件到当前操作目录中
ftp.retrbinary('RETR %s' % filename, open(filename, 'wb').write)
#ftp.storbinary('STOR %s'% filename, open(filename, 'rb'), CONST_BUFFER_SIZE) FTP上传文件
# 导入数据
self.import_data(os.path.join(os.getcwd(), filename))
new_filename = os.path.splitext(filename)[0] + "_FINISHED" + os.path.splitext(filename)[1]
# 修改FTP目录上的文件名称,使用新的文件名称
ftp.rename(filename, new_filename)
finally:
# 删除当前目录中下载的文件明细
os.remove(os.path.join(os.getcwd(), filename))
ftp.quit()
参考文档:
http://doublewei369.blog.163.com/blog/static/342947812012923113356945/
http://blog.csdn.net/wklken/article/details/7059423
http://wangwei007.blog.51cto.com/68019/983638