How to check the remote path - is it a file or directory?

I use SFTPClient to download files from a remote server. But I do not know if the remote path is a file or directory. If the remote path is a directory, I need to recursively process this directory.

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 find the problem: the os.path.isfile or os.path.isdir returns False , so I think these functions cannot work for remotePath.

+11
source share
3 answers

os.path.isfile() and os.path.isdir() work only with local names.

Instead, I would use the sftp.listdir_attr() function and load the full SFTPAttributes objects and check their st_mode attribute using 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)) 
+24
source

use stat module

 import stat for file in sftp.listdir(remotePath): if stat.S_ISREG(sftp.stat(os.path.join(remotePath, file)).st_mode): try: sftp.get(file, os.path.join(localPath, file)) except: pass 
+4
source

The following are the steps that you must follow to check if the remote path is FILE or LIST:

1) Create a connection to the remote

 transport = paramiko.Transport((hostname,port)) transport.connect(username = user, password = pass) sftp = paramiko.SFTPClient.from_transport(transport) 

2) Suppose you have the directory "/ root / testing /" and you want to check the ur.Import stat code

 import stat 

3) Use the following logic to check if its file or directory is

 fileattr = sftp.lstat('root/testing') if stat.S_ISDIR(fileattr.st_mode): print 'is Directory' if stat.S_ISREG(fileattr.st_mode): print 'is File' 
+3
source

Source: https://habr.com/ru/post/951615/


All Articles