当前位置:网站首页>FTP, SFTP file transfer
FTP, SFTP file transfer
2022-07-04 19:27:00 【I don't hate mortals】
ftp
#!/usr/bin/python
# -*- coding: UTF-8 -*-
from ftplib import FTP
import os
class MyFtp:
def __init__(self, host=None, port=21, username=None, password=None):
self.ftp = FTP()
# Reset the encoding
self.ftp.encoding = 'utf-8'
try:
# 0 Active mode 1 # Passive mode
self.ftp.set_pasv(True)
self.ftp.connect(host, port)
self.ftp.login(username, password)
print(' Successfully connected to :', host, " Login successful ...")
except Exception as err:
print("FTP Connection or login failed , The error is described as :", err)
def __del__(self):
print(" Close the connection ")
self.ftp.quit()
def is_same_size(self, local_file, remote_file):
# Determine whether the file size is equal
try:
remote_file_size = self.ftp.size(remote_file)
except Exception as err:
# print("is_same_size() The error is described as :%s" % err)
remote_file_size = -1
try:
local_file_size = os.path.getsize(local_file)
except Exception as err:
# print("is_same_size() The error is described as :%s" % err)
local_file_size = -1
# print(f'local_file_size:{local_file_size}, remote_file_size:{remote_file_size}')
if remote_file_size == local_file_size:
return 1
else:
return 0
def download_file(self, remote_file, local_file):
remote_file = remote_file if self.ftp.pwd() == "/" else self.ftp.pwd() + "/" + remote_file
print(f" Download the file : {remote_file} ---> {local_file}")
if self.is_same_size(local_file, remote_file):
print(" Same file size , This file skipped ")
else:
try:
buf_size = 1024
file_handler = open(local_file, 'wb')
self.ftp.retrbinary(f'RETR {remote_file}', file_handler.write, blocksize=buf_size)
file_handler.close()
except Exception as err:
print(f' Error downloading file , Something unusual happened :{err}')
def download_dir(self, remote_dir, local_dir):
remote_dir = remote_dir if self.ftp.pwd() == "/" else self.ftp.pwd() + "/" + remote_dir
print(f" Download directory : {remote_dir} ---> {local_dir}")
try:
self.ftp.cwd(remote_dir)
print(f' Switch to the directory : {self.ftp.pwd()}')
except Exception as err:
print(f' Remote directory {remote_dir} non-existent , continue ..., The specific error is described as :{err}')
return
os.makedirs(local_dir, exist_ok=True)
remote_dirs = []
self.ftp.dir(".", remote_dirs.append)
remote_list = list(map(lambda x: x.split()[-1], remote_dirs))
print(f' Remote directory list : {remote_list}')
for remote_detail in remote_dirs:
file_type = remote_detail[0]
file_name = remote_detail.split()[-1]
local_path = os.path.join(local_dir, file_name)
if file_type == "d":
self.download_dir(file_name, local_path)
elif file_type == '-':
self.download_file(file_name, local_path)
self.ftp.cwd("..")
print(" Return to the upper directory : ", self.ftp.pwd())
def upload_file(self, local_file, remote_file):
# Upload files
remote_file = remote_file if self.ftp.pwd() == "/" else self.ftp.pwd() + "/" + remote_file
print(f" Upload files : {local_file} ---> {remote_file}")
if not os.path.isfile(local_file):
print(f'{local_file} non-existent ')
return
if self.is_same_size(local_file, remote_file):
print(' Same file size , This file skipped ')
return
try:
buf_size = 1024
file_handler = open(local_file, 'rb')
self.ftp.storbinary(f'STOR {remote_file}', file_handler, buf_size)
file_handler.close()
except Exception as err:
print(f' Error uploading file , Something unusual happened :{err}')
def upload_dir(self, local_dir, remote_dir):
# Upload directory
remote_dir = remote_dir if self.ftp.pwd() == "/" else self.ftp.pwd() + "/" + remote_dir
print(f" Upload directory : {local_dir} ---> {remote_dir}")
if not os.path.isdir(local_dir):
print(f' Local directory {local_dir} non-existent ')
return
try:
self.ftp.mkd(remote_dir)
except Exception as err:
print(f" Create a remote directory {remote_dir} Failure , The error is described as :{err}")
return
self.ftp.cwd(remote_dir)
print(' Switch to remote directory : ', self.ftp.pwd())
local_name_list = os.listdir(local_dir)
print(" Local directory list : ", local_name_list)
for local_name in local_name_list:
local_name_path = os.path.join(local_dir, local_name)
if os.path.isdir(local_name_path):
self.upload_dir(local_name_path, local_name)
else:
self.upload_file(local_name_path, local_name)
self.ftp.cwd("..")
print(" Return to the upper directory : ", self.ftp.pwd())sftp
#!/usr/bin/python
# coding=utf-8
import paramiko
import os
import stat
class MySftp:
def __init__(self, host=None, port=22, username=None, password=None):
self.sftp_connect = paramiko.Transport((host, port))
self.sftp_connect.connect(username=username, password=password)
self.sftp = paramiko.SFTPClient.from_transport(self.sftp_connect)
print(' Successfully connected to :', host, " Login successful ...")
def __del__(self):
print(" Close the connection ")
self.sftp_connect.close()
def is_same_size(self, local_file, remote_file):
# Determine whether the file size is equal
try:
remote_file_size = self.sftp.stat(remote_file).st_size
except Exception as err:
# print("is_same_size() The error is described as :%s" % err)
remote_file_size = -1
try:
local_file_size = os.path.getsize(local_file)
except Exception as err:
# print("is_same_size() The error is described as :%s" % err)
local_file_size = -1
# print(f'local_file_size:{local_file_size}, remote_file_size:{remote_file_size}')
if remote_file_size == local_file_size:
return 1
else:
return 0
def download_file(self, remote_file, local_file):
remote_file = self.sftp.getcwd() + "/" + remote_file if self.sftp.getcwd() else remote_file
print(f" Download the file :{remote_file} ---> {local_file}")
if self.is_same_size(local_file, remote_file):
print(" The file already exists and the file already exists and the file size is the same , This file skipped ")
return
try:
self.sftp.get(remote_file, local_file)
except Exception as err:
print(f' Error downloading file , Something unusual happened :{err}')
def download_dir(self, remote_dir, local_dir):
remote_dir = self.sftp.getcwd() + "/" + remote_dir if self.sftp.getcwd() else remote_dir
print(f" Download directory : {remote_dir} ---> {local_dir}")
try:
self.sftp.chdir(remote_dir)
print(f' Switch to the directory : {self.sftp.getcwd()}')
except Exception as err:
print(f' Remote directory {remote_dir} non-existent , continue ..., The specific error is described as :{err}')
return
os.makedirs(local_dir, exist_ok=True)
remote_dirs = self.sftp.listdir(remote_dir)
print(f' Remote directory list : {remote_dirs}')
for remote_path in remote_dirs:
local_path = os.path.join(local_dir, remote_path)
if str(self.sftp.stat(remote_path))[0] == "d":
self.download_dir(remote_path, local_path)
elif str(self.sftp.stat(remote_path))[0] == "-":
self.download_file(remote_path, local_path)
self.sftp.chdir("..")
print(" Return to the upper directory : ", self.sftp.getcwd())
def upload_file(self, local_file, remote_file):
remote_file = self.sftp.getcwd() + "/" + remote_file if self.sftp.getcwd() else remote_file
print(f" Upload files : {local_file} ---> {remote_file}")
if not os.path.isfile(local_file):
print(f" Local files {local_file} non-existent ")
return
if self.is_same_size(local_file, remote_file):
print(' The file already exists and the file size is the same , This file skipped ')
return
try:
self.sftp.put(local_file, remote_file)
except Exception as err:
print(f' Error uploading file , Something unusual happened :{err}')
def upload_dir(self, local_dir, remote_dir):
remote_dir = self.sftp.getcwd() + "/" + remote_dir if self.sftp.getcwd() else remote_dir
print(f" Upload directory : {local_dir} ---> {remote_dir}")
if not os.path.isdir(local_dir):
print(f' Local directory {local_dir} non-existent ')
return
if not self.is_sftp_dir(remote_dir):
self.sftp.mkdir(remote_dir)
self.sftp.chdir(remote_dir)
print(' Switch to remote directory : ', self.sftp.getcwd())
local_name_list = os.listdir(local_dir)
print(" Local directory list : ", local_name_list)
for local_name in local_name_list:
local_name_path = os.path.join(local_dir, local_name)
if os.path.isdir(local_name_path):
self.upload_dir(local_name_path, local_name)
else:
self.upload_file(local_name_path, local_name)
self.sftp.chdir("..")
print(" Return to the upper directory : ", self.sftp.getcwd())
def is_sftp_dir(self, remote_dir):
try:
if stat.S_ISDIR(self.sftp.stat(remote_dir).st_mode): # If remote_dir Exists and is a directory , Then return to True
return True
except:
return False边栏推荐
- Wechat reading notes of "work, consumerism and the new poor"
- 利用策略模式优化if代码【策略模式】
- Stream流
- 26. Delete the duplicate item C solution in the ordered array
- 26. 删除有序数组中的重复项 C#解答
- The 15th youth informatics competition in Shushan District in 2019
- .NET ORM框架HiSql实战-第二章-使用Hisql实现菜单管理(增删改查)
- Technology sharing | interface testing value and system
- LeetCode FizzBuzz C#解答
- Go microservice (II) - detailed introduction to protobuf
猜你喜欢

大div中有多个div,这些div在同一行显示,溢出后产生滚动条而不换行

【uniapp】uniapp开发app在线预览pdf文件

物联网应用技术的就业前景和现状

更安全、更智能、更精致,长安Lumin完虐宏光MINI EV?

神经网络物联网应用技术就业前景【欢迎补充】

LeetCode第300场周赛(20220703)

自由小兵儿
![[uniapp] uniapp development app online Preview PDF file](/img/11/d640338c626249057f7ad616b55c4f.png)
[uniapp] uniapp development app online Preview PDF file

A method of using tree LSTM reinforcement learning for connection sequence selection

Scala basic tutorial -- 19 -- actor
随机推荐
2022 ByteDance daily practice experience (Tiktok)
[uniapp] uniapp development app online Preview PDF file
一文掌握数仓中auto analyze的使用
Shell programming core technology "four"
BI技巧丨权限轴
添加命名空间声明
Mxnet implementation of googlenet (parallel connection network)
Shell programming core technology II
Lex and yacc based lexical analyzer + parser
[发布] 一个测试 WebService 和数据库连接的工具 - DBTest v1.0
redis分布式锁的8大坑总结梳理
26. 删除有序数组中的重复项 C#解答
LeetCode第300场周赛(20220703)
Caché WebSocket
神经网络物联网应用技术学什么
神经网络物联网应用技术就业前景【欢迎补充】
Shell 編程核心技術《四》
与二值化阈值处理相关的OpenCV函数、方法汇总,便于对比和拿来使用
[mathematical basis of machine learning] (I) linear algebra (Part 1 +)
使用SSH