簡體   English   中英

如何檢查遠程路徑是文件還是目錄?

[英]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.isfileos.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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM