#_*_coding:utf-8 -*-
from ftplib import FTP
import time
import tarfile
import os
import sys
import socket
import ftplib
class Myftp:
def __init__(self,host,username,password):
self.host=host
self.port=21
self.username=username
self.password=password
self.ftp=FTP()
self.bufsize= 8192
def login(self):
try:
self.ftp.connect(self.host,self.port)
self.ftp.login(self.username,self.password)
print("\033[32m ftp:"+self.host+" Login Success!!"+"\033[0m")
except ZeroDivisionError as e:
print("\033[31m"+e+"\033[0m")
return 1
return 0
#从ftp下载文件
def downloadfile(self,remotepath,localpath):
#下载文件
#remotepath:远程端文件名
#localpath:本地文件名
#设置的缓冲区大小
try:
fp=open(localpath,"wb")
self.ftp.retrbinary('RETR '+remotepath,fp.write,self.bufsize)
self.ftp.set_debuglevel(0)#参数0,关闭调试模式
fp.close()
#self.ftp.close()
print("\033[32mDownLoad %s %sFile Success!!\033[0m"%(remotepath,localpath))
return 0
except ZeroDivisionError as e:
print("\033[31m%s\033[0m"%(e))
return 1
#从本地上传文件到ftp
def uploadfile(self,remotepath,localpath):
#上传文件
#remotepath:远程端文件名
#localpath:本地文件名
#设置的缓冲区大小
try:
fp=open(localpath,'rb')
self.ftp.storbinary('STOR '+remotepath,fp,self.bufsize)
self.ftp.set_debuglevel(0)
#self.ftp.close()
print("\033[32mUpload %s %s File Success!!\033[0m"%(localpath,remotepath))
return 0
except ZeroDivisionError as e:
print("\033[31m%s\033[0m"%(e))
return 1
#从ftp批量下载文件
def downloadfiles(self,remotepath,localpath):
#批量下载
#remotepath:远程端文件名
#localpath:本地文件名
#设置的缓冲区大小
try:
if not os.path.isdir(localpath):#判断目录是否存在,不存在创建
os.mkdir(localpath)
pwd_path=self.ftp.pwd()
print("ftp Current Path:",pwd_path)
self.ftp.cwd(remotepath)#设置ftp当前操作的路径
filename_list=self.ftp.nlst()#返回一个文件列表
for i in filename_list:#读取目录下所有文件名
self.downloadfile(remotepath+i,localpath+i)
#self.ftp.close()
except ZeroDivisionError as e:
print("\033[31m%s\033[0m"%(e))
return 1
return 0
#从本地批量上传文件
def uploadfiles(self,remotepath,localpath):
#批量上传
#remotepath:远程端文件名
#localpath:本地文件名
#设置的缓冲区大小
try:
#判断目录是否存在
try:
self.ftp.cwd(remotepath)
except ftplib.error_perm:
self.ftp.mkd(remotepath)#不存在目录创建
for filename in os.listdir(localpath):#获取当前目录文件名
pathfilename=os.path.join(localpath,filename)#获取文件名
self.uploadfile(remotepath+filename,pathfilename)
except ZeroDivisionError as e:
print("\033[31m%s\033[0m"%(e))
return 1
return 0
def is_same_size(self,local_file,remote_file):#比较文件大小
#local_file:本地文件
#remote_file:ftp服务器文件
#remote_file_size:ftp服务器文件大小
#local_file_size:本地文件大小
try:
remote_file_size=self.ftp.size(remote_file)#获取ftp文件大小
except Exception as err:
print("\033[31mis_same_size() 错误描述为:%s\033[0m"%(err))
return 1
try:
local_file_size=os.path.getsize(local_file)#获取本地文件大小
except Exception as err:
print("\033[31mis_same_size() 错误描述为:%s\033[0m"%(err))
return 1
if remote_file_size==local_file_size:
print("\033[32m"+local_file+" And "+remote_file+ " Compare Succeed!!\033[0m")
return 0
else:
print("\033[31m"+local_file+" And "+remote_file+ " Compare Fail!!\033[0m")
return 1
#