import os标签:remote,进度条,local,ssh,file,path,上传,size From: https://www.cnblogs.com/daien522556/p/17756646.html
import paramiko
import time
def download_file_with_progress(hostname, port, username, password, remote_path, local_path):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=hostname, port=port, username=username, password=password)
sftp = ssh.open_sftp()
# get remote file size
remote_file_size = sftp.stat(remote_path).st_size
print("remote_file_size:{}".format(remote_file_size))
# print progress
with open(local_path, 'wb') as f:
def callback(transferred, remote_file_size):
percent = float(transferred) * 100 / remote_file_size
print("Download %.2f%% of the file." % percent)
# transfer 32768 bytes as SSH slice, get remote file to local
sftp.getfo(remote_path, f, callback=callback)
sftp.close()
ssh.close()
def upload_file_with_progress(hostname, username, password, remote_path, local_path):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=hostname, username=username, password=password)
sftp = ssh.open_sftp()
# get local file size
local_file_size = os.stat(local_path).st_size
print("local_file_size:{}".format(local_file_size))
# print progress
lst = []
try:
with open(local_path, 'rb') as f:
def callback(transferred, local_file_size):
percent = int(float(transferred) * 100 / local_file_size)
if percent not in lst:
lst.append(percent)
if percent == 5:
sftp.remove(remote_path)
raise
print("Upload %.2f%% of the file." % percent)
# transfer 32768 bytes as SSH slice, put local file to remote
sftp.putfo(f, remote_path, local_file_size, callback=callback)
except Exception as e:
print("error:",e)
finally:
sftp.close()
ssh.close()
if __name__ == "__main__":
# hostname = "*****"
hostname = "*********"
port = 22
# username = "********"
username = "*******"
# password = "*****"
password = "*********"
remote_path = "/F:/liu/test_ssh/mibcsv.csv"
local_path = "./mibcsv.csv"
# # download file and calculate cost
# print("Download Start, 32678 bytes as default SSH slice: ")
# download_start = time.time()
# download_file_with_progress(hostname, port, username, password, remote_path, local_path)
# download_end = time.time()
# download_cost = download_end - download_start
# print("Download successfully! Cost {}s".format(download_cost))
#
# cutline = '\033[32;1m%s\033[0m' % '=' * 100
# print(cutline)
# upload file and calculate cost
print("Upload Start, 32678 bytes as default SSH slice: ")
# remote_path_upload = "/F:/liu/test_ssh/anconda"
remote_path_upload = "/F:/liu/test_ssh/anconda"
local_path_upload = "./anconda"
upload_start = time.time()
upload_file_with_progress(hostname, username, password, remote_path_upload, local_path_upload)
upload_end = time.time()
upload_cost = upload_end - upload_start
print("Upload successfully! Cost {}s".format(upload_cost))