Recursive directory download with Paramiko?

后端 未结 6 1504
甜味超标
甜味超标 2020-11-30 10:23

I want to download a directory with unknown contents recursively via SSH and have been trying Paramiko. I have seen several examples how to upload directories but none that

相关标签:
6条回答
  • 2020-11-30 11:00

    You can use the stat() method of your sftp object:

    http://www.lag.net/paramiko/docs/paramiko.SFTPClient-class.html

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

    Paramiko does not support recursive operations.

    You can use pysftp. It's a wrapper around Paramiko that has more Python-ish look and feel and supports recursive operations. See

    • pysftp.Connection.put_r()
    • pysftp.Connection.get_r()

    Or you can just base your code on pysftp source code. Or see my answer to Python pysftp get_r from Linux works fine on Linux but not on Windows.

    0 讨论(0)
  • 2020-11-30 11:12

    An old question, but a solution I came up with that works quite well, it's a little bit sloppy (typecasting and slashes and all) - but it does work.

    Note this uses fabric.api.local to make the directories in the destination.

    def sftp_get_recursive(path, dest, sftp=sftp):
        item_list = sftp.listdir(path)
        dest = str(dest)
    
        if not os.path.isdir(dest):
            local("mkdir %s" % dest)
    
        for item in item_list:
            item = str(item)
    
            if is_directory(path + "/" + item, sftp):
                sftp_get_recursive(path + "/" + item, dest + "/" + item, sftp)
            else:
                sftp.get(path + "/" + item, dest + "/" + item)
    
    0 讨论(0)
  • 2020-11-30 11:22

    stat() method among other attributes returns permissions. d (for example drwxrwxrwx) shows that it is directory.

    As example:

    dir = oct(sftp.stat(path).st_mode)
    print dir[0:2]
    

    output interpritation: 01 fifo 02 character special 04 directory 06 block special 10 regular file 12 symbolic link 14 socket

    0 讨论(0)
  • 2020-11-30 11:23

    If u using Linux or Unix-like. U can use 'file' utility with popen. Or simple u can use os.path.isdir() =)

    0 讨论(0)
  • 2020-11-30 11:26
    from stat import S_ISDIR
    
    def isdir(path):
      try:
        return S_ISDIR(sftp.stat(path).st_mode)
      except IOError:
        #Path does not exist, so by definition not a directory
        return False
    

    ...assuming sftp is an open Paramiko SFTP connection.

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