代码如下:
import paramiko
import os
from ftplib import FTP
import paramiko, os
import json
def ftpDownloadFile(ftp, ftpfile, localfile):
bufsize = 1024
with open(localfile, 'wb') as fid:
ftp.retrbinary('RETR {0}'.format(ftpfile), fid.write, bufsize)
return True
def ftpConnect(ftpserver, port, usrname, password):
"""
:param ftpserver: 服务器IP
:param port: 端口
:param usrname: 用户名
:param password: 密码
:return:
"""
ftp = FTP()
try:
ftp.connect(ftpserver, port)
ftp.login(usrname, password)
except:
raise IOError('\n FTP connection failed, please check the code!')
else:
print(ftp.getwelcome())
print('\n+------- ftp connection successful!!! --------+')
return ftp
def ftpDisConnect(ftp):
ftp.quit()
def ssh_upload(from_path, to_file_name, ip='你的第三个服务器的IP地址', port=22, username='你的第三个服务器的用户名', password='你的第三个服务器的密码',to_path='/data1/auth-priv/ftper/yxd/2022/1'):
"""
:param from_path: 要上传的文件路径
:param to_file_name: 带后缀的文件命(注意不带父级目录)
:param ip: 服务器的IP地址
:param port: 服务器的端口
:param username: 服务器的用户名
:param password: 服务器的密码
:param to_path: 要上传的文件的路径(到文件后缀名的父级目录)
:return:
"""
transport = paramiko.Transport((ip, port))
transport.connect(username=username, password=password)
sftp = paramiko.SFTPClient.from_transport(transport)
sftp.put(from_path, os.path.join(to_path, to_file_name))
sftp.close()
transport.close()
if __name__ == "__main__":
fromPath = "2022/01/"
ftpserver = '存储文件的服务器的IP地址(第一个服务器)'
port = 21
usrname = ''
pwd = ''
dir_list = os.listdir(fromPath)
try:
with open('/home/xy/ftper/yxd/2021/record.json', 'r') as f:
file_name_list = json.load(f)
except Exception as e:
file_name_list = []
for each_dir in dir_list:
if each_dir not in file_name_list:
file_name_list.append(each_dir)
json.dump(file_name_list, open('/home/xy/ftper/yxd/2021/record.json', 'a'))
ftp = ftpConnect(ftpserver, 21, usrname, pwd)
result = ftpDownloadFile(ftp, fromPath+each_dir, '/home/xy/ftper/yxd/2021/'+each_dir.split('/')[-1])
ftpDisConnect(ftp)
print(each_dir, '下载完成')
ssh_upload('/home/xy/ftper/yxd/2021/'+each_dir.split('/')[-1], each_dir)
print(each_dir, '上传已完成')
os.remove('/home/xy/ftper/yxd/2021/'+each_dir.split('/')[-1])
print(each_dir, '删除已完成')
|