pythonsshsftpparamiko

Python Paramiko directory walk over SFTP


How to do os.walk() but on another computer through SSH? The problem is that os.walk() executes on a local machine and I want to ssh to another host, walk through a directory and generate MD5 hashes for every file within.

What I wrote so far looks like this (below code) but it doesn't work. Any help would be greatly appreciated.

try:
    hash_array = []
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect('sunbeam', port=22, username='xxxx', password='filmlight')

    spinner.start()
    for root, dirs, files in os.walk(_path):
        for file in files:
            file_path = os.path.join(os.path.abspath(root), file)
            
            #  generate hash code for file
            hash_array.append(genMD5hash(file_path))
            
            file_nb += 1
    spinner.stop()
    spinner.ok('Finished.')

    return hash_array
except Exception as e:
    print(e)
    return None
finally:
    ssh.close() 

Solution

  • To recursively list a directory using Paramiko, with a standard file access interface, the SFTP, you need to implement a recursive function with a use of SFTPClient.listdir_attr:

    from stat import S_ISDIR, S_ISREG
    
    def listdir_r(sftp, remotedir):
        for entry in sftp.listdir_attr(remotedir):
            remotepath = remotedir + "/" + entry.filename
            mode = entry.st_mode
            if S_ISDIR(mode):
                listdir_r(sftp, remotepath)
            elif S_ISREG(mode):
                print(remotepath)
    

    Based on Python pysftp get_r from Linux works fine on Linux but not on Windows.


    Alternatively, pysftp implements an os.walk equivalent: Connection.walktree. Though pysftp is dead, so better use it only as an inspiration for your own implementation, not directly.


    But you will have troubles getting MD5 of a remote file with SFTP protocol.

    While Paramiko supports it with its SFTPFile.check, most SFTP servers (particularly the most widespread SFTP/SSH server – OpenSSH) do not. See:
    How to check if Paramiko successfully uploaded a file to an SFTP server? and
    How to perform checksums during a SFTP file transfer for data integrity?

    So you will most probably have to resort to using shell md5sum command (if you have a shell access at all). And once you have to use the shell anyway, consider listing the files with shell, as that will be magnitudes faster then via SFTP.

    See md5 all files in a directory tree.

    Use SSHClient.exec_command:
    Comparing MD5 of downloaded files against files on an SFTP server in Python


    Obligatory warning: Do not use AutoAddPolicy – You are losing a protection against MITM attacks by doing so. For a correct solution, see Paramiko "Unknown Server".