Python使用sftp實現上傳和下載功能

在Python中可以使用paramiko模塊中的sftp登陸遠程主機,實現上傳和下載功能。

1.功能實現

  1. 根據輸入參數判斷是文件還是目錄,進行上傳和下載
  2. 本地參數local需要與遠程參數remote類型一致,文件以文件名結尾,目錄以\結尾
  3. 上傳和下載的本地和遠程目錄需要存在
  4. 異常捕獲

2.代碼實現

#!/usr/bin/python
# coding=utf-8

import paramiko
import os

def sftp_upload(host,port,username,password,local,remote):
    sf = paramiko.Transport((host,port))
    sf.connect(username = username,password = password)
    sftp = paramiko.SFTPClient.from_transport(sf)
    try:
        if os.path.isdir(local):#判斷本地參數是目錄還是文件
            for f in os.listdir(local):#遍歷本地目錄
                sftp.put(os.path.join(local+f),os.path.join(remote+f))#上傳目錄中的文件
        else:
            sftp.put(local,remote)#上傳文件
    except Exception,e:
        print('upload exception:',e)
    sf.close()

def sftp_download(host,port,username,password,local,remote):
    sf = paramiko.Transport((host,port))
    sf.connect(username = username,password = password)
    sftp = paramiko.SFTPClient.from_transport(sf)
    try:
        if os.path.isdir(local):#判斷本地參數是目錄還是文件
            for f in sftp.listdir(remote):#遍歷遠程目錄
                 sftp.get(os.path.join(remote+f),os.path.join(local+f))#下載目錄中文件
        else:
            sftp.get(remote,local)#下載文件
    except Exception,e:
        print('download exception:',e)
    sf.close()

if __name__ == '__main__':
    host = '192.168.1.2'#主機
    port = 22 #端口
    username = 'root' #用戶名
    password = '123456' #密碼
    local = 'F:\\sftptest\\'#本地文件或目錄,與遠程一致,當前爲windows目錄格式,window目錄中間需要使用雙斜線
    remote = '/opt/tianpy5/python/test/'#遠程文件或目錄,與本地一致,當前爲linux目錄格式
    sftp_upload(host,port,username,password,local,remote)#上傳
    #sftp_download(host,port,username,password,local,remote)#下載

3.總結
以上代碼實現了文件和目錄的上傳和下載,可以單獨上傳和下載文件,也可以批量上傳和下載目錄中的文件,基本實現了所要的功能,但是針對目錄不存在的情況,以及上傳和下載到多臺主機上的情況,還有待完善。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章