如何使用 SCP 或 SSH 将完整目录递归复制到 Python (paramiko) 中的远程服务器?

How to copy a complete directory recursively to a remote server in Python (paramiko) using SCP or SSH?

我的本地计算机上有一个包含一些文件和子目录的目录,该目录由每日 Python 脚本 运行ning 生成。然后我想将目录中所有生成的文件复制到服务器,然后使用 python package paramiko.运行 通过 ssh 在其上执行 运行 一些命令。

我想添加少量代码,使用 python 的 paramiko 包,通过 SSH/SCP 将整个目录及其中的文件和子目录安全地复制到我的服务器。我可以使用相同的方式发送单个文件,但无法使用 paramiko 发送整个目录及其内容。它给我 IOError 说这是一个目录。

IOError: [Errno 21] Is a directory: 'temp'

这是我的代码:

from paramiko import SSHClient, AutoAddPolicy
from scp import SCPClient

class SSh(object):

    def __init__(self, address, username, password, port=22):
        print "Connecting to server."
        self._address = address
        self._username = username
        self._password = password
        self._port = port
        self.sshObj = None
        self.connect()
        self.scp = SCPClient(self.sshObj.get_transport())

    def sendCommand(self, command):
        if(self.sshObj):
            stdin, stdout, stderr = self.sshObj.exec_command(command)
            while not stdout.channel.exit_status_ready():
                # Print data when available
                if stdout.channel.recv_ready():
                    alldata = stdout.channel.recv(1024)
                    prevdata = b"1"
                    while prevdata:
                        prevdata = stdout.channel.recv(1024)
                        alldata += prevdata

                    print str(alldata)
        else:
            print "Connection not opened."

    def connect(self):
        try:
            ssh = SSHClient()
            ssh.set_missing_host_key_policy(AutoAddPolicy())
            ssh.connect(self._address, port=self._port, username=self._username, password=self._password, timeout=20, look_for_keys=False)
            print 'Connected to {} over SSh'.format(self._address)
            return True
        except Exception as e:
            ssh = None
            print "Unable to connect to {} over ssh: {}".format(self._address, e)
            return False
        finally:
            self.sshObj = ssh

if __name__ == "__main__":
    # Parse and check the arguments
    ssh = SSh('10.24.143.190', 'username', 'password')
    ssh.scp.put("Valigrind_BB.py") # This works perfectly fine
    ssh.scp.put("temp") # IOError over here Is a directory
    ssh.sendCommand('ls')

提前致谢。

查看 SCP 的源代码,您似乎可以将参数 "recursive" 作为布尔值传递给 put() 方法,以指定递归地传输目录的内容。 Here 是我正在谈论的源代码的 link。尝试将代码的最后一部分更改为以下内容:

if __name__ == "__main__":
    # Parse and check the arguments
    ssh = SSh('10.24.143.190', 'username', 'password')
    ssh.scp.put("Valigrind_BB.py") # This works perfectly fine
    ssh.scp.put("temp", recursive=True) # IOError over here Is a directory
    ssh.sendCommand('ls')

此外,如果您只想传输文件,可以尝试使用 rsync 作为替代方案。不过,对上面代码的修改应该可以。希望对您有所帮助。