Crabar Crabar - 5 days ago 6
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)


or

sftp.get_d(main_path + dirpath, local_path)


With
get_r
I am getting FileNotFound exception. With
get_d
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

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):
        return
    if not os.path.exists(local_path):
        os.makedirs(local_path)

    dirlist = sftp.listdir(remotepath=full_path)
    for i in dirlist:
        if sftp.isdir(full_path + '/' + i):
            grab_dir_rec(sftp, dirpath + '/' + i)
        else:
            grab_file(sftp, dirpath + '/' + i)
Comments