繁体   English   中英

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

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

我的本地计算机上有一个包含一些文件和子目录的目录,该目录由日常运行的Python脚本生成。 然后,我想将目录中所有这些生成的文件复制到服务器,然后使用python软件包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()方法,以指定递归传输目录的内容。 这里是我正在谈论的源代码的链接。 尝试将代码的最后一部分更改为以下内容:

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作为替代。 修改上面的代码应该可以。 我希望这有帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM