Crabar Crabar - 1 year ago 100
Python Question

Recursive download with pysftp

I'm trying to fetch from ftp next structure:

= main_dir/

== dir1/

=== file1

== dir2/

=== file2

I tried to achieve this with commands below:

sftp.get_r(main_path + dirpath, local_path)


sftp.get_d(main_path + dirpath, local_path)

I am getting FileNotFound exception. With
I am getting empty dir (when target dir have files not dirs, it works fine).

I'm totally sure that directory exists at this path. What am I doing wrong?

Answer Source

I didn't understand why it doesn't work so I ended with my own recursive solution:

def grab_dir_rec(sftp, dirpath):
    local_path = target_path + dirpath
    full_path = main_path + dirpath
    if not sftp.exists(full_path):
    if not os.path.exists(local_path):

    dirlist = sftp.listdir(remotepath=full_path)
    for i in dirlist:
        if sftp.isdir(full_path + '/' + i):
            grab_dir_rec(sftp, dirpath + '/' + i)
            grab_file(sftp, dirpath + '/' + i)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download