python - How to check a remote path is a file or a directory? -
i using sftpclient
download files remote server. cann't know remote path file or directoty. if remote path directory need handle directory recursive.
this code:
def downloadfile(sftp, remotepath, localpath): file in sftp.listdir(remotepath): if os.path.isfile(os.path.join(remotepath, file)): # file, try: sftp.get(file, os.path.join(localpath, file)) except: pass elif os.path.isdir(os.path.join(remotepath, file)): # dir, need 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 problem: function os.path.isfile
or os.path.isdir
return false
, think these function cann't work remotepath.
os.path.isfile()
, os.path.isdir()
work on local filenames.
i'd use sftp.listdir_attr()
function instead , load full sftpattributes
objects, , inspect st_mode
attribute stat
module utility functions:
import stat def downloadfile(sftp, remotepath, localpath): fileattr in sftp.listdir_attr(remotepath): if stat.s_isdir(fileattr.st_mode): sftp.get(fileattr.filename, os.path.join(localpath, fileattr.filename))
Comments
Post a Comment