Python - SFTP



SFTP 又稱為 SSH 檔案傳輸協議。它是一種網路協議,透過任何可靠資料流提供檔案訪問、檔案傳輸和檔案管理。該程式透過安全通道執行,例如 SSH 伺服器已對客戶端進行了身份驗證,並且可以在協議中獲取客戶端使用者身份。

pysftp 模組是一個 SFTP 簡單介面。該模組提供高階抽象和基於任務的例程來處理 SFTP 需求。因此,我們使用以下命令將其模組安裝到我們的 python 環境中。

pip install pysftp

示例

在下例中,我們使用 sftp 登入到遠端伺服器,然後在該目錄中獲取和放置一些檔案。

import pysftp

with pysftp.Connection('hostname', username='me', password='secret') as sftp:

    with sftp.cd('/allcode'):           # temporarily chdir to allcode
        sftp.put('/pycode/filename')  	# upload file to allcode/pycode on remote
        sftp.get('remote_file')         # get a remote file

當我們執行上面的程式碼,我們能夠看到當前目錄中存在的檔案列表,並且可以在該目錄中放置和獲取一些檔案。

廣告