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

Bla*_*mba 11 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)
Run Code Online (Sandbox Code Playgroud)

我发现问题:函数os.path.isfileos.path.isdir返回False,所以我认为这些函数不能用于remotePath.

Mar*_*ers 27

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))
Run Code Online (Sandbox Code Playgroud)


小智 5

要验证远程路径是 FILE 还是 DIRECTORY,要遵循以下步骤:

1)建立远程连接

transport = paramiko.Transport((hostname,port))
transport.connect(username = user, password = pass)
sftp = paramiko.SFTPClient.from_transport(transport)
Run Code Online (Sandbox Code Playgroud)

2)假设你有目录“/root/testing/”,你想检查你的代码。导入stat包

import stat
Run Code Online (Sandbox Code Playgroud)

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' 
Run Code Online (Sandbox Code Playgroud)