使用python登录ftp并自动下载目录

主要支持的命令如下所示

    cd      进入文件夹
    delete      删除文件
    dir     获取当前文件列表
    get     下载文件
    help        帮助
    mkdir       创建文件夹
    put     上传文件
    pwd     获取当前目录
    rename      重命名文件
    rmdir       删除文件夹
    size        获取文件大小

python ftp 模块主要的函数及功能

from ftplib import FTP      #加载ftp模块
ftp=FTP()                   #设置变量
ftp.set_debuglevel(2)       #打开调试级别2,显示详细信息
ftp.set_pasv(0)                 #0主动模式 1 #被动模式
ftp.connect("IP","port")    #连接的ftp sever和端口
ftp.login("user","password")#连接的用户名,密码
print ftp.getwelcome()      #打印出欢迎信息
ftp.cmd("xxx/xxx")          #更改远程目录
bufsize=1024                #设置的缓冲区大小
filename="filename.txt"     #需要下载的文件
file_handle=open(filename,"wb").write                   #以写模式在本地打开文件
ftp.retrbinaly("RETR filename.txt",file_handle,bufsize) #接收服务器上文件并写入本地文件
ftp.set_debuglevel(0)       #关闭调试模式
ftp.quit                    #退出ftp

ftp.dir()                   #显示目录下文件信息
ftp.mkd(pathname)           #新建远程目录
ftp.pwd()                   #返回当前所在位置
ftp.rmd(dirname)            #删除远程目录
ftp.delete(filename)        #删除远程文件
ftp.rename(fromname, toname)#将fromname修改名称为toname。
ftp.storbinaly("STOR filename.txt",file_handel,bufsize) #上传目标文件

好了,代码如下

#coding=gbk
#author:liangliang
#email:liangliangyy@gmail.com
#blog:http://www.lylinux.org/

from ftplib import FTP
import os,sys,string,datetime,time
import socket

class MYFTP:
	def __init__(self, hostaddr, username, password, remotedir, port=21):
		self.hostaddr = hostaddr
		self.username = username
		self.password = password
		self.remotedir  = remotedir
		self.port     = port
		self.ftp      = FTP()
		self.file_list = []
		# self.ftp.set_debuglevel(2)
	def __del__(self):
		self.ftp.close()
		# self.ftp.set_debuglevel(0)
	def login(self):
		ftp = self.ftp
		try: 
			timeout = 60
			socket.setdefaulttimeout(timeout)
			ftp.set_pasv(True)
			print '开始连接到 %s' %(self.hostaddr)
			ftp.connect(self.hostaddr, self.port)
			print '成功连接到 %s' %(self.hostaddr)
			print '开始登录到 %s' %(self.hostaddr)
			ftp.login(self.username, self.password)
			print '成功登录到 %s' %(self.hostaddr)
			debug_print(ftp.getwelcome())
		except Exception:
			deal_error("连接或登录失败")
		try:
			ftp.cwd(self.remotedir)
		except(Exception):
			deal_error('切换目录失败')

	def is_same_size(self, localfile, remotefile):
		try:
			remotefile_size = self.ftp.size(remotefile)
		except:
			remotefile_size = -1
		try:
			localfile_size = os.path.getsize(localfile)
		except:
			localfile_size = -1
		debug_print('lo:%d  re:%d' %(localfile_size, remotefile_size),)
		if remotefile_size == localfile_size:
		 	return 1
		else:
			return 0
	def download_file(self, localfile, remotefile):
		if self.is_same_size(localfile, remotefile):
		 	debug_print('%s 文件大小相同,无需下载' %localfile)
		 	return
		else:
			debug_print('>>>>>>>>>>>>下载文件 %s ... ...' %localfile)
		#return
		file_handler = open(localfile, 'wb')
		self.ftp.retrbinary('RETR %s'%(remotefile), file_handler.write)
		file_handler.close()

	def download_files(self, localdir='./', remotedir='./'):
		try:
			self.ftp.cwd(remotedir)
		except:
			debug_print('目录%s不存在,继续...' %remotedir)
			return
		if not os.path.isdir(localdir):
			os.makedirs(localdir)
		debug_print('切换至目录 %s' %self.ftp.pwd())
		self.file_list = []
		self.ftp.dir(self.get_file_list)
		remotenames = self.file_list
		#print(remotenames)
		#return
		for item in remotenames:
			filetype = item[0]
			filename = item[1]
			local = os.path.join(localdir, filename)
			if filetype == 'd':
				self.download_files(local, filename)
			elif filetype == '-':
				self.download_file(local, filename)
		self.ftp.cwd('..')
		debug_print('返回上层目录 %s' %self.ftp.pwd())
	def upload_file(self, localfile, remotefile):
		if not os.path.isfile(localfile):
			return
		if self.is_same_size(localfile, remotefile):
		 	debug_print('跳过[相等]: %s' %localfile)
		 	return
		file_handler = open(localfile, 'rb')
		self.ftp.storbinary('STOR %s' %remotefile, file_handler)
		file_handler.close()
		debug_print('已传送: %s' %localfile)
	def upload_files(self, localdir='./', remotedir = './'):
		if not os.path.isdir(localdir):
			return
		localnames = os.listdir(localdir)
		self.ftp.cwd(remotedir)
		for item in localnames:
			src = os.path.join(localdir, item)
			if os.path.isdir(src):
				try:
					self.ftp.mkd(item)
				except:
					debug_print('目录已存在 %s' %item)
				self.upload_files(src, item)
			else:
				self.upload_file(src, item)
		self.ftp.cwd('..')

	def get_file_list(self, line):
		ret_arr = []
		file_arr = self.get_filename(line)
		if file_arr[1] not in ['.', '..']:
			self.file_list.append(file_arr)
			
	def get_filename(self, line):
		pos = line.rfind(':')
		while(line[pos] != ' '):
			pos += 1
		while(line[pos] == ' '):
			pos += 1
		file_arr = [line[0], line[pos:]]
		return file_arr
def debug_print(s):
	print (s)
def deal_error(e):
	timenow  = time.localtime()
	datenow  = time.strftime('%Y-%m-%d', timenow)
	logstr = '%s 发生错误: %s' %(datenow, e)
	debug_print(logstr)
	file.write(logstr)
	sys.exit()

if __name__ == '__main__':
	file = open("log.txt", "a")
	timenow  = time.localtime()
	datenow  = time.strftime('%Y-%m-%d', timenow)
	logstr = datenow
	# 配置如下变量
	hostaddr = 'host' # ftp地址
	username = 'username' # 用户名
	password = 'password' # 密码
	port  =  21   # 端口号 
	rootdir_local  = '.' + os.sep + 'bak/' # 本地目录
	rootdir_remote = '/public_html/'          # 远程目录
	
	f = MYFTP(hostaddr, username, password, rootdir_remote, port)
	f.login()
	f.download_files(rootdir_local, rootdir_remote)
	
	timenow  = time.localtime()
	datenow  = time.strftime('%Y-%m-%d', timenow)
	logstr += " - %s 成功执行了备份\n" %datenow
	debug_print(logstr)
	
	file.write(logstr)
	file.close()

使用python登录ftp并自动下载目录》上有4条评论

发表评论

电子邮件地址不会被公开。 必填项已用*标注