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.