可以使用處理ftp
或檔傳輸協議的python模組將數據上傳到伺服器。
需要安裝模組ftplib
才能實現上面功能。
pip install ftplib
1. 使用ftplib
在下面的示例中,使用FTP方法連接到伺服器,然後提供用戶憑據。接下來,我們提到檔的名稱以及在伺服器中發送和存儲檔的storbinary
方法。
import ftplib
ftp = ftplib.FTP("127.0.0.1")
ftp.login("username", "mypassword")
file = open('index.html','rb')
ftp.storbinary("STOR " + file, open(file, "rb"))
file.close()
ftp.quit()
當運行上述程式時,我們觀察到該檔的副本已在伺服器中創建。
2. 使用ftpreety
與ftplib
相似,可以使用ftpreety
安全地連接到遠程伺服器並上傳檔。可以使用ftpreety
下載檔。下麵的程式相象相同。
from ftpretty import ftpretty
# Mention the host
host = "127.0.0.1"
# Supply the credentisals
f = ftpretty(host, user, pass )
# Get a file, save it locally
f.get('someremote/file/on/server.txt', '/tmp/localcopy/server.txt')
# Put a local file to a remote location
# non-existent subdirectories will be created automatically
f.put('/tmp/localcopy/data.txt', 'someremote/file/on/server.txt')
當運行上述程式時,可以看到該檔的副本已在伺服器中創建。
上一篇:
Python Web伺服器
下一篇:
Python代理伺服器