[英]How to check a remote path is a file or a directory?
我正在使用SFTPClient
从远程服务器下载文件。 但我不知道远程路径是文件还是目录。 如果远程路径是一个目录,我需要递归处理这个目录。
这是我的代码:
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)
我发现了问题:函数os.path.isfile
或os.path.isdir
返回False
,所以我认为这些函数不能用于 remotePath。
os.path.isfile()
和os.path.isdir()
仅适用于本地文件名。
我会改用sftp.listdir_attr()
函数并加载完整的SFTPAttributes
对象,并使用stat
模块实用程序函数检查它们的st_mode
属性:
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))
要验证远程路径是 FILE 还是 DIRECTORY,要遵循以下步骤:
1)建立远程连接
transport = paramiko.Transport((hostname,port))
transport.connect(username = user, password = pass)
sftp = paramiko.SFTPClient.from_transport(transport)
2)假设你有目录“/root/testing/”,你想检查你的代码。导入stat包
import stat
3)使用以下逻辑检查其文件或目录
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'
使用模块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
也许这个解决方案? 如果您需要与列表目录结合,这不是正确的一种,而是一种可能。
is_directory = False
try:
sftp.listdir(path)
is_directory = True
except IOError:
pass
return is_directory
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.