1. 程式人生 > >python連線sftp下載檔案及資料夾

python連線sftp下載檔案及資料夾

# coding=utf-8
import paramiko
import os

def DownLoadFile(sftp,LocalFile,RemoteFile):  # 下載當個檔案
    file_handler = open(LocalFile, 'wb')
    print(file_handler)
    sftp.get(RemoteFile, LocalFile)  # 下載目錄中檔案
    file_handler.close()
    return True

def DownLoadFileTree(sftp, LocalDir, RemoteDir):  # 下載整個目錄下的檔案
    if not os.path.exists(LocalDir):
        os.makedirs(LocalDir)
    for file in sftp.listdir(RemoteDir):
        Local = os.path.join(LocalDir, file)
        Remote=os.path.join(RemoteDir, file)
        if file.find(".") == -1:#判斷是否是檔案
            if not os.path.exists(Local):
                os.makedirs(Local)
            DownLoadFileTree(sftp,Local, Remote)
        else:#檔案
            DownLoadFile(sftp,Local, Remote)
    return "complete"

if __name__ == '__main__':
  host = ' '#主機
  port =  #埠
  username = '' #使用者名稱
  password = '' #密碼
  sf = paramiko.Transport((host, port))
  sf.connect(username=username, password=password)
  sftp = paramiko.SFTPClient.from_transport(sf)
  local = 'D:\datadisk2_hdf5'#本地檔案
  remote = '\SH-2-0'#遠端檔案或目錄
  DownLoadFileTree(sftp,local,remote)#下載