Python pysftp put_r does not work on Windows

I cannot reproduce your exact problem, but indeed the recursive functions of pysftp are known to be implemented in a way that makes them fail on Windows (or any system that does not use *nix-like path syntax).

Pysftp uses os.sep and os.path functions for remote SFTP paths, what is wrong, as SFTP paths always use a forward slash.


But you can easily implement a portable replacement:

import os
def put_r_portable(sftp, localdir, remotedir, preserve_mtime=False):
    for entry in os.listdir(localdir):
        remotepath = remotedir + "/" + entry
        localpath = os.path.join(localdir, entry)
        if not os.path.isfile(localpath):
            try:
                sftp.mkdir(remotepath)
            except OSError:     
                pass
            put_r_portable(sftp, localpath, remotepath, preserve_mtime)
        else:
            sftp.put(localpath, remotepath, preserve_mtime=preserve_mtime)    

Use it like:

put_r_portable(sftp, sftp_local_path, sftp_remote_path, preserve_mtime=False) 

Note that the above code can be easily modified to work with Paramiko directly, in case you do not want to use pysftp. The Paramiko SFTPClient class also has the put method. The only difference is that the Paramiko’s put does not have the preserve_mtime parameter/functionality (but it can be implemented easily, if you need it).


For a similar question about get_r, see:
Python pysftp get_r from Linux works fine on Linux but not on Windows

Leave a Comment