How to check a remote path is a file or a directory?
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))
Below steps to be followed to verify if remote path is FILE or DIRECTORY:
1) Create connection with remote
transport = paramiko.Transport((hostname,port))
transport.connect(username = user, password = pass)
sftp = paramiko.SFTPClient.from_transport(transport)
2) Suppose you have directory "/root/testing/" and you would like to check through ur code.Import stat package
import stat
3) Use below logic to check if its file or Directory
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'
use module stat
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