欢迎访问宙启技术站
智能推送

Python编写SCP文件上传下载进度显示脚本

发布时间:2024-01-09 21:56:08

下面是一个使用Python编写的SCP文件上传和下载进度显示脚本的示例代码:

import paramiko
import sys
import os

class SCPFileTransfer:
    def __init__(self, hostname, username, password):
        self.hostname = hostname
        self.username = username
        self.password = password
        self.port = 22

    def upload_file(self, local_path, remote_path):
        try:
            ssh_client = paramiko.SSHClient()
            ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            ssh_client.connect(hostname=self.hostname, port=self.port,
                               username=self.username, password=self.password)
            sftp_client = ssh_client.open_sftp()
            filesize = os.stat(local_path).st_size
            sftp_client.put(local_path, remote_path, callback=self.progress_bar,
                            confirm=True, filesize=filesize)
            ssh_client.close()
        except Exception as e:
            print("Exception:", str(e))

    def download_file(self, remote_path, local_path):
        try:
            ssh_client = paramiko.SSHClient()
            ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            ssh_client.connect(hostname=self.hostname, port=self.port,
                               username=self.username, password=self.password)
            sftp_client = ssh_client.open_sftp()
            filesize = sftp_client.stat(remote_path).st_size
            sftp_client.get(remote_path, local_path, callback=self.progress_bar,
                            confirm=True, filesize=filesize)
            ssh_client.close()
        except Exception as e:
            print("Exception:", str(e))

    def progress_bar(self, current, total):
        percent = (current / total) * 100
        sys.stdout.write("\rUploading/downloading file... %.2f%% complete" % percent)
        sys.stdout.flush()


# 使用示例
hostname = 'your_hostname'
username = 'your_username'
password = 'your_password'

# 创建一个SCPFileTransfer对象
scp = SCPFileTransfer(hostname, username, password)

# 上传文件
local_path = '/path/to/local/file.txt'
remote_path = '/path/to/remote/file.txt'
scp.upload_file(local_path, remote_path)

# 下载文件
remote_path = '/path/to/remote/file.txt'
local_path = '/path/to/local/file.txt'
scp.download_file(remote_path, local_path)

在示例代码中,我们首先创建了一个名为SCPFileTransfer的类,其中包含了上传和下载文件的方法。在这些方法中,我们使用paramiko库来进行SCP文件传输。在上传和下载文件的过程中,我们通过设置callback参数来显示上传和下载的进度条。

然后,我们创建了一个SCPFileTransfer对象,并在使用示例中使用该对象来上传和下载文件。需要注意的是,你需要将hostnameusernamepassword替换为你的实际值,以及将local_pathremote_path替换为实际的本地和远程文件路径。

使用这个脚本,你可以方便地在Python中实现SCP文件的上传和下载,并显示传输的进度条。