Directory transfers with Paramiko

前端 未结 10 867
刺人心
刺人心 2020-11-30 07:25

How do you use Paramiko to transfer complete directories? I\'m trying to use:

sftp.put(\"/Folder1\",\"/Folder2\")

which is giving me this e

相关标签:
10条回答
  • 2020-11-30 08:14

    I don't think you can do that. Look up the documentation for os.walk and copy each file "manually".

    0 讨论(0)
  • 2020-11-30 08:16

    Here's my piece of code:

    import errno
    import os
    import stat
    
    def download_files(sftp_client, remote_dir, local_dir):
        if not exists_remote(sftp_client, remote_dir):
            return
    
        if not os.path.exists(local_dir):
            os.mkdir(local_dir)
    
        for filename in sftp_client.listdir(remote_dir):
            if stat.S_ISDIR(sftp_client.stat(remote_dir + filename).st_mode):
                # uses '/' path delimiter for remote server
                download_files(sftp_client, remote_dir + filename + '/', os.path.join(local_dir, filename))
            else:
                if not os.path.isfile(os.path.join(local_dir, filename)):
                    sftp_client.get(remote_dir + filename, os.path.join(local_dir, filename))
    
    
    def exists_remote(sftp_client, path):
        try:
            sftp_client.stat(path)
        except IOError, e:
            if e.errno == errno.ENOENT:
                return False
            raise
        else:
            return True
    
    0 讨论(0)
  • 2020-11-30 08:16

    Works for me doing something like this, all folder and files are copied to the remote server.

    parent = os.path.expanduser("~")
    for dirpath, dirnames, filenames in os.walk(parent):
        remote_path = os.path.join(remote_location, dirpath[len(parent)+1:])
            try:
                ftp.listdir(remote_path)
            except IOError:
                ftp.mkdir(remote_path)
    
            for filename in filenames:
                ftp.put(os.path.join(dirpath, filename), os.path.join(remote_path, filename))
    
    0 讨论(0)
  • 2020-11-30 08:20

    As far as I know, Paramiko does not support recursive file upload. However, I have found a solution for recursive upload using Paramiko here. Follows an excerpt of their recursive upload function:

       def _send_recursive(self, files):
            for base in files:
                lastdir = base
                for root, dirs, fls in os.walk(base):
                    # pop back out to the next dir in the walk
                    while lastdir != os.path.commonprefix([lastdir, root]):
                        self._send_popd()
                        lastdir = os.path.split(lastdir)[0]
                    self._send_pushd(root)
                    lastdir = root
                    self._send_files([os.path.join(root, f) for f in fls])
    

    You may try to either use their function SCPClient.put invoking the above function for recursive upload or implement it on your own.

    0 讨论(0)
提交回复
热议问题