2013-08-13 16 views
6

tôi đang sử dụng SFTPClient để tải xuống tệp từ máy chủ từ xa. Nhưng tôi không thể biết con đường từ xa là một tập tin hoặc một directoty. nếu đường dẫn từ xa là một thư mục tôi cần để xử lý thư mục này đệ quy.Cách kiểm tra đường dẫn từ xa là một tệp hoặc một thư mục?

đây là mã của tôi:

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) 

tôi tìm ra vấn đề: chức năng os.path.isfile hoặc os.path.isdir trở False, vì vậy tôi nghĩ rằng những chức năng cann't làm việc cho remotePath.

+0

kiểm tra mở rộng đường dẫn nếu có phần mở rộng hoặc. – SANDEEP

+2

Tệp không nhất thiết phải có phần mở rộng. – Noctua

+1

có thể trùng lặp của [sử dụng st \ _mode để xác định tệp hoặc thư mục] (http://stackoverflow.com/questions/15861967/using-st-mode-to-identify-file-or-directory) –

Trả lời

17

os.path.isfile()os.path.isdir() chỉ hoạt động trên tên địa phương tên tệp.

Tôi muốn sử dụng chức năng sftp.listdir_attr() thay vào đó và tải đầy đủ SFTPAttributes đối tượng, và kiểm tra thuộc tính st_mode của họ với các chức năng tiện ích stat mô-đun:

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

sử dụng mô-đun 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 
0

Dưới bước để được theo dõi để xác minh xem đường dẫn từ xa là FILE hay DIRECTORY:

1) Tạo kết nối với xa

transport = paramiko.Transport((hostname,port)) 
transport.connect(username = user, password = pass) 
sftp = paramiko.SFTPClient.from_transport(transport) 

2) Giả sử bạn có thư mục "/ root/thử nghiệm /" và bạn muốn kiểm tra thông qua ur gói stat code.Import

import stat 

3) Sử dụng dưới logic để kiểm tra xem tệp của nó hoặc Thư mục

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'