Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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() 
like image 844
michal-ko Avatar asked Jun 19 '19 15:06

michal-ko


2 Answers

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 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 even have a shell access). 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".

like image 64
Martin Prikryl Avatar answered Oct 27 '22 09:10

Martin Prikryl


Based on the previous answer, here a version that does not require recursivity and returns a list of paths instead using the print command.

from stat import S_ISDIR, S_ISREG
from collections import deque

def listdir_r(sftp, remotedir):
    dirs_to_explore = deque([remotedir])
    list_of_files = deque([])

    while len(dirs_to_explore) > 0:
        current_dir = dirs_to_explore.popleft()

        for entry in sftp.listdir_attr(current_dir):
            current_fileordir = current_dir + "/" + entry.filename

            if S_ISDIR(entry.st_mode):
                dirs_to_explore.append(current_fileordir)
            elif S_ISREG(entry.st_mode):
                list_of_files.append(current_fileordir)

    return list(list_of_files)
like image 38
Alfonso Sancho Avatar answered Oct 27 '22 08:10

Alfonso Sancho