在網(wǎng)上找了好多都不靠譜雹顺,要不就是報錯要不就是只能創(chuàng)建個文件夾瘸恼,于是自己怒改了一個儿咱。
#! /usr/bin/env python2.7
# encoding=utf8
from ftplib import FTP,error_perm # 加載ftp模塊
import os
class FTPSync(object):
conn = FTP()
def __init__(self,host,port=21):
self.conn.connect(host,port)
def login(self,username,password):
self.conn.login(username,password)
self.conn.encoding = "GB2312"
self.conn.set_debuglevel(2) #打開調(diào)試級別2,顯示詳細信息
self.conn.set_pasv(True)
#0主動模式 1 #被動模式
print(self.conn.welcome)
def _ftp_list(self,line):
li = line.split(' ')
if self.ftp_dir_name == li[-1] and "<DIR>" in li:
self._is_dir = True
def _is_ftp_file(self, ftp_path):
try:
if ftp_path in self.conn.nlst(os.path.dirname(ftp_path)):
return True
else:
return False
except error_perm as e:
return False
def _is_ftp_dir(self,ftp_path):
"""
用來判斷所給的路徑是文件還是文件夾
"""
ftp_path = ftp_path.rstrip('/')
ftp_parent_path = os.path.dirname(ftp_path)
self.ftp_dir_name = os.path.basename(ftp_path)
self._is_dir = False
if ftp_path == '.' or ftp_path == './' or ftp_path == '':
self._is_dir = True
else:
try:
self.conn.cwd(ftp_path)
self._is_dir = True
# self.conn.retrlines('LIST %s' %ftp_parent_path,self._ftp_list)
except error_perm as e:
return self._is_dir
return self._is_dir
def get_file(self,ftp_path="",local_path="."):
print(ftp_path)
ftp_path = ftp_path.rstrip('/')
file_name = os.path.basename(ftp_path)
# 如果本地路徑是目錄噪叙,下載文件到該目錄
if os.path.isdir(local_path):
file_handler = open(os.path.join(local_path,file_name),'wb')
self.conn.retrbinary("RETR %s"%(ftp_path),file_handler.write)
file_handler.close()
# 如果本地路徑不是目錄渐裂,但上層目錄存在豺旬,則按照本地路徑的文件名作為下載的文件名稱
elif os.path.isdir(os.path.dirname(local_path)):
file_handler = open(local_path,'wb')
self.conn.retrbinary("RETR %s"%(ftp_path),file_handler.write)
file_handler.close()
# 如果本地路徑不是目錄,且上層目錄不存在柒凉,則退出
else:
print('EROOR:The dir:%s is not exist' %os.path.dirname(local_path))
def get_dir(self,ftp_path,local_path=".",begin=True):
if not self._is_ftp_dir(ftp_path):
self.get_file(ftp_path=ftp_path, local_path=local_path)
return
if begin:
local_path = os.path.join(local_path, os.path.basename(ftp_path))
#如果本地目錄不存在族阅,則創(chuàng)建目錄
if not os.path.isdir(local_path):
os.mkdir(local_path)
#進入ftp目錄,開始遞歸查詢
self.conn.cwd(ftp_path)
ftp_files = self.conn.nlst()
for file in ftp_files:
local_file = os.path.join(local_path, file)
#如果file ftp路徑是目錄則遞歸上傳目錄(不需要再進行初始化begin的標(biāo)志修改為False)
#如果file ftp路徑是文件則直接上傳文件
if self._is_ftp_dir(file):
self.get_dir(file, local_file, False)
elif "idea" in file:
pass
else:
self.get_file(ftp_path=file, local_path=local_file)
#如果當(dāng)前ftp目錄文件已經(jīng)遍歷完畢返回上一層目錄
self.conn.cwd("..")
def get_all_dir(self):
ftp_files = self.conn.nlst()
for file in ftp_files:
self.get_dir(file,"D:\\ftp",True)
def put_file(self,local_path,ftp_path="."):
ftp_path = ftp_path.rstrip('/')
if os.path.isfile(local_path):
file_handler = open(local_path,'rb')
local_file_name = os.path.basename(local_path)
#如果遠程路徑是個目錄膝捞,則上傳文件到這個目錄坦刀,文件名不變
if self._is_ftp_dir(ftp_path):
self.conn.storbinary('STOR %s'%os.path.join(ftp_path,local_file_name), file_handler)
#如果遠程路徑的上層是個目錄,則上傳文件绑警,文件名按照給定命名
elif self._is_ftp_dir(os.path.dirname(ftp_path)):
print('STOP %s'%ftp_path)
self.conn.storbinary('STOR %s'%ftp_path, file_handler)
#如果遠程路徑不是目錄求泰,且上一層的目錄也不存在,則提示給定遠程路徑錯誤
else:
print('STOR %s'%ftp_path, file_handler)
def put_dir(self,local_path,ftp_path=".",begin=True):
ftp_path = ftp_path.rstrip('/')
if not os.path.isdir(local_path):
print('ERROR:The dir:%s is not exist' %local_path)
return
#當(dāng)本地目錄存在時上傳
#上傳初始化:如果給定的ftp路徑不存在需要創(chuàng)建计盒,同時將本地的目錄存放在給定的ftp目錄下。
# 本地目錄下文件存放的路徑為ftp_path = ftp_path + os.path.basename(local_path)
#例如芽丹,將本地的文件夾a上傳到ftp的a/b目錄下北启,則本地a目錄下的文件將上傳的ftp的a/b/a目錄下
if begin:
if not self._is_ftp_dir(ftp_path):
try:
self.conn.mkd(ftp_path)
except Exception,e:
pass
ftp_path = os.path.join(ftp_path,os.path.basename(local_path))
# 如果上傳路徑是文件夾,則創(chuàng)建目錄
if not self._is_ftp_dir(ftp_path):
try:
self.conn.mkd(ftp_path)
except Exception, e:
pass
#進入本地目錄,開始遞歸查詢
os.chdir(local_path)
local_files = os.listdir('.')
for file in local_files:
ftp_file = os.path.join(ftp_path,file)
#如果file本地路徑是目錄則遞歸上傳文件(不需要再進行初始化begin的標(biāo)志修改為False)
#如果file本地路徑是文件則直接上傳文件
if os.path.isdir(file):
self.put_dir(file,ftp_file,False)
elif "idea" in file:
pass
else:
self.put_file(file,ftp_path)
#如果當(dāng)前本地目錄文件已經(jīng)遍歷完畢返回上一層目錄
os.chdir('..')
if __name__ == "__main__":
ftp = FTPSync('10.10.10.69')
ftp.login('dong',"dong")
# ftp.get_file("ftppath")
# ftp.get_dir("ftppath","localpath",True)
# ftp.get_dir("","",True)
# ftp.get_all_dir("")
ftp.put_file('/home/myscan/myscan/myscan/report_file/7/http___192.168.1.104_.html')
# ftp.put_dir('/home/myscan/myscan/myscan/report_file/7', "/home/ftp_dong",begin=True)