Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check a remote path is a file or a directory?

I am using SFTPClient to download files from the remote server. However, I don't know if the remote path is a file or a directory. If the remote path is a directory, I need to handle this directory recursively.

This is my code:

def downLoadFile(sftp, remotePath, localPath):
    for file in sftp.listdir(remotePath):  
        if os.path.isfile(os.path.join(remotePath, file)): # file, just get
            try:
                sftp.get(file, os.path.join(localPath, file))
            except:
                pass
        elif os.path.isdir(os.path.join(remotePath, file)): # dir, need to handle recursive
            os.mkdir(os.path.join(localPath, file))
            downLoadFile(sftp, os.path.join(remotePath, file), os.path.join(localPath, file))

if __name__ == '__main__':
    paramiko.util.log_to_file('demo_sftp.log')
    t = paramiko.Transport((hostname, port))
    t.connect(username=username, password=password)
    sftp = paramiko.SFTPClient.from_transport(t)

I found the problem: The function os.path.isfile or os.path.isdir returns False. So, it looks like these functions can not work for remotePath.

like image 739
BlackMamba Avatar asked Aug 13 '13 09:08

BlackMamba


People also ask

How do you check if a path is directory or file?

To check if the path you have is a file or directory, import os module and use isfile() method to check if it is a file, and isdir() method to check if it is a directory.

What is a remote file path?

This path parser is used by all filesystem utility programs. It accepts paths in the remote path format. In this format, a full absolute path is given as hostname:path , where hostname is the hostname of a distributed filesystem naming server, and path is an absolute path to a file or directory on that naming server.


1 Answers

os.path.isfile() and os.path.isdir() only work on local filenames.

I'd use the sftp.listdir_attr() function instead and load full SFTPAttributes objects, and inspect their st_mode attribute with the stat module utility functions:

import stat

def downLoadFile(sftp, remotePath, localPath):
    for fileattr in sftp.listdir_attr(remotePath):  
        if stat.S_ISDIR(fileattr.st_mode):
            sftp.get(fileattr.filename, os.path.join(localPath, fileattr.filename))
like image 101
Martijn Pieters Avatar answered Oct 16 '22 09:10

Martijn Pieters