如何检查远程路径是文件还是目录?

时间:2013-08-13 09:44:42

标签: python paramiko

我正在使用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.isfileos.path.isdir返回False,所以我认为这些函数不适用于remotePath。

4 个答案:

答案 0 :(得分:24)

os.path.isfile()os.path.isdir()仅适用于本地文件名。

我将使用sftp.listdir_attr()函数并加载完整的SFTPAttributes个对象,并使用st_mode模块实用程序函数检查其stat属性:

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))

答案 1 :(得分:4)

使用模块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

答案 2 :(得分:3)

要遵循以下步骤来验证远程路径是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' 

答案 3 :(得分:0)

也许这个解决方案?如果您需要与列表目录结合,这不是正确的一种而是可能的一种。

    is_directory = False

    try:
        sftp.listdir(path)
        is_directory = True
    except IOError:
        pass

    return is_directory
相关问题