写这篇文章方便以后遇到需要定期去上传或下载时直接可以此简单模板。
1.python中FTP上传
#/usr/bin/python # -*- coding: utf-8 -*- import datetime import time import sys import os import ftplib def Upload_File(): ftp = ftplib.FTP() TODAY=time.strftime(‘%Y-%m-%d‘) FTPIP= "10.10.10.10" #FTP地址 FTPPORT= 21 #FTP端口号 USERNAME= "user" #FTP用户名 USERPWD= "passwd" #FTP密码 ftp.connect(FTPIP, FTPPORT) ftp.login(USERNAME,USERPWD) ftp.set_pasv(0) #打开主动模式 CURRTPATH= "log" LPath="/data/python/study/" ftp.cwd(CURRTPATH) os.chdir(LPath) UploadLocalFilename=LPath+"code"+TODAY+".txt" f=open(UploadLocalFilename,‘rb‘) ftp.storbinary(‘STOR codes.py‘,f,1024) #ftp.storbinary(‘STOR %s‘ % os.path.basename(UploadLocalFilename),f,1024) f.close() ftp.close() Upload_File() #调用函数
2.python中FTP下载
#!/usr/bin/python # -*- coding: utf-8 -*- import sys import ftplib import datetime import os import commands def Down_File(): ftp=ftplib.FTP() DATE=datetime.date.today().strftime("%y%m%d") RPATH="hunk" LPATH="/home/website/imoney/log" FTPIP="10.10.10.10" FTPPORT= 21 USERNAME= "user" USERPWD= "passwd" ftp.connect(FTPIP, FTPPORT) ftp.login(USERNAME,USERPWD) ftp.set_pasv(0) #打开主动模式 ftp.cwd(RPATH) os.chdir(LPATH) DownLocalFilename="access% s_log.gz" %DATE f = open(DownLocalFilename, ‘wb‘) DownRoteFilename="access% s_log.gz" %DATE try: ftp.retrbinary(‘RETR ‘ + DownRoteFilename ,f.write,1024) #可以下载较大文件 except Exception,e: print "Down access% s_log.gz is error: " %DATE+str(e) sys.exit() f.close() ftp.close() Down_File() #调用函数
时间: 2024-10-20 11:45:33