python本身自带一个FTP模块,可以轻松实现FTP的上传,下载等操作。下面来看看用法:
# 来自jb51.cc
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) # 创建目录
一个上传代码:
# 来自jb51.cc
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()