基于python實(shí)現(xiàn)FTP文件上傳與下載操作(ftp&sftp協(xié)議)
前言 FTP(File Transfer Protocol)是文件傳輸協(xié)議的簡稱。用于Internet上的控制文件的雙向傳輸。同時(shí),它也是一個(gè)應(yīng)用程序(Application)。用戶可以通過它把自己的PC機(jī)與世界各地所有運(yùn)行FTP協(xié)議的服務(wù)器相連,訪問服務(wù)器上的大量程序和信息。如果用戶需要將文件從自己的計(jì)算機(jī)上發(fā)送到另一臺(tái)計(jì)算機(jī)上,可使用FTP上傳(upload)或(put)操作,而更多種的情況是用戶使用FTP下載(download)或獲?。╣et)操作從FTP服務(wù)器上下載文件
在傳輸文件時(shí)我們可能會(huì)選擇sftp和ftp兩種協(xié)議中的一種,兩者的主要區(qū)別在于安全與傳輸速度,F(xiàn)TP傳輸數(shù)據(jù)的過程,他們在不同協(xié)議下的默認(rèn)端口號是不同的,它有兩種傳輸模式:主動(dòng)傳輸模式(PORT)和被動(dòng)傳輸模式(PASSIVE,簡稱PASV),關(guān)于FTP相關(guān)內(nèi)容這里就不做詳細(xì)數(shù)明了,這里將以python語言實(shí)現(xiàn)其功能
一 、基于ftp協(xié)議
Python中默認(rèn)安裝的ftplib模塊定義了FTP類,其中函數(shù)有限,可用來實(shí)現(xiàn)簡單的ftp客戶端,用于上傳或下載文件,函數(shù)列舉如下
ftp登陸連接
from ftplib import FTP #加載ftp模塊
ftp=FTP() #設(shè)置變量
ftp.set_debuglevel(2) #打開調(diào)試級別2,顯示詳細(xì)信息
ftp.connect(“IP”,“port”) #連接的ftp sever和端口
ftp.login(“user”,“password”) #連接的用戶名,密碼
print ftp.getwelcome() #打印出歡迎信息
ftp.cmd(“xxx/xxx”) #進(jìn)入遠(yuǎn)程目錄
bufsize=1024 #設(shè)置的緩沖區(qū)大小
filename=“filename.txt” #需要下載的文件
file_handle=open(filename,“wb”).write #以寫模式在本地打開文件
ftp.retrbinaly(“RETR filename.txt”,file_handle,bufsize) #接收服務(wù)器上文件并寫入本地文件
ftp.set_debuglevel(0) #關(guān)閉調(diào)試模式
ftp.quit() #退出ftp
ftp相關(guān)命令操作
ftp.cwd(pathname) #設(shè)置FTP當(dāng)前操作的路徑
ftp.dir() #顯示目錄下所有目錄信息
ftp.nlst() #獲取目錄下的文件
ftp.mkd(pathname) #新建遠(yuǎn)程目錄
ftp.pwd() #返回當(dāng)前所在位置
ftp.rmd(dirname) #刪除遠(yuǎn)程目錄
ftp.delete(filename) #刪除遠(yuǎn)程文件
ftp.rename(fromname, toname)#將fromname修改名稱為toname。
ftp.storbinaly(“STOR filename.txt”,file_handel,bufsize) #上傳目標(biāo)文件
ftp.retrbinary(“RETR filename.txt”,file_handel,bufsize) #下載FTP文件
#!/usr/bin/env python
#coding:utf-8
from ctypes import *
import os
import sys
import ftplib
import time
today = time.strftime('%Y%m%d',time.localtime(time.time()))
ip = '111.111.111.6'
username = 'ftpUserName'
password = 'ftpPassWord'
filename = '203200189'+ today + 'A001.tar.gz'
src_file = '/ftpFilePath/'+filename
class myFtp:
ftp = ftplib.FTP()
ftp.set_pasv(False)
def __init__(self, host, port=21):
self.ftp.connect(host, port)
def Login(self, user, passwd):
self.ftp.login(user, passwd)
print(self.ftp.welcome)
def DownLoadFile(self, LocalFile, RemoteFile): #下載指定目錄下的指定文件
file_handler = open(LocalFile, 'wb')
print(file_handler)
# self.ftp.retrbinary("RETR %s" % (RemoteFile), file_handler.write)#接收服務(wù)器上文件并寫入本地文件
self.ftp.retrbinary('RETR ' + RemoteFile, file_handler.write)
file_handler.close()
return True
def DownLoadFileTree(self, LocalDir, RemoteDir): # 下載整個(gè)目錄下的文件
print("remoteDir:", RemoteDir)
if not os.path.exists(LocalDir):
os.makedirs(LocalDir)
self.ftp.cwd(RemoteDir)
RemoteNames = self.ftp.nlst()
print("RemoteNames", RemoteNames)
for file in RemoteNames:
Local = os.path.join(LocalDir, file)
print(self.ftp.nlst(file))
if file.find(".") == -1:
if not os.path.exists(Local):
os.makedirs(Local)
self.DownLoadFileTree(Local, file)
else:
self.DownLoadFile(Local, file)
self.ftp.cwd("..")
return True
#從本地上傳文件到ftp
def uploadfile(self, remotepath, localpath):
bufsize = 1024
fp = open(localpath, 'rb')
ftp.storbinary('STOR ' + remotepath, fp, bufsize)
ftp.set_debuglevel(0)
fp.close()
def close(self):
self.ftp.quit()
if __name__ == "__main__":
ftp = myFtp(ip)
ftp.Login(username, password)
ftp.DownLoadFile(filename,src_file )
#ftp.DownLoadFileTree('.', '/cteidate/')
ftp.close()
print("ok!")
二 、基于sftp協(xié)議
在Python中可以使用paramiko模塊中的sftp登陸遠(yuǎn)程主機(jī),實(shí)現(xiàn)上傳和下載功能。
#!/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):#判斷本地參數(shù)是目錄還是文件
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):#判斷本地參數(shù)是目錄還是文件
for f in sftp.listdir(remote):#遍歷遠(yuǎn)程目錄
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 = '111.111.1111.2'#主機(jī)
port = 22 #端口
username = 'root' #用戶名
password = '123456' #密碼
local = '/sftptest/'#本地文件或目錄,與遠(yuǎn)程一致,若當(dāng)前為windows目錄格式,window目錄中間需要使用雙斜線
remote = '/opt/test/'#遠(yuǎn)程文件或目錄,與本地一致,當(dāng)前為linux目錄格式
sftp_upload(host,port,username,password,local,remote)#上傳
#sftp_download(host,port,username,password,local,remote)#下載
總結(jié):
在python中這兩種協(xié)議實(shí)現(xiàn)文件的上傳與下載需要引入不同的模塊,實(shí)現(xiàn)起來還是比較簡單的,相關(guān)模塊里的源碼也是比較清晰。因?yàn)槲倚枰氖敲刻於〞r(shí)下載文件,所以是在linux配置的定時(shí)每天早晨6點(diǎn)執(zhí)行該python腳本的任務(wù),所以文件名都是用日期命名的。
TP.quit()與FTP.close()的區(qū)別
FTP.quit():發(fā)送QUIT命令給服務(wù)器并關(guān)閉掉連接。這是一個(gè)比較“緩和”的關(guān)閉連接方式,但是如果服務(wù)器對QUIT命令返回錯(cuò)誤時(shí),會(huì)拋出異常。
FTP.close():單方面的關(guān)閉掉連接,不應(yīng)該用在已經(jīng)關(guān)閉的連接之后,例如不應(yīng)用在FTP.quit()之后。
到此這篇關(guān)于基于python實(shí)現(xiàn)FTP文件上傳與下載操作(ftp&sftp協(xié)議)的文章就介紹到這了,更多相關(guān)python 實(shí)現(xiàn)ftp文件上傳下載內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Python辦公自動(dòng)化從Excel中計(jì)算整理數(shù)據(jù)并寫入Word
- Python辦公自動(dòng)化Word轉(zhuǎn)Excel文件批量處理
- Python辦公自動(dòng)化批量處理文件實(shí)現(xiàn)示例
- Python自動(dòng)化辦公之手機(jī)號提取
- Python自動(dòng)化辦公之Word文件內(nèi)容的讀取
- Python使用sftp實(shí)現(xiàn)傳文件夾和文件
- Python使用sftp實(shí)現(xiàn)上傳和下載功能
- python實(shí)現(xiàn)自動(dòng)下載sftp文件
- python paramiko利用sftp上傳目錄到遠(yuǎn)程的實(shí)例
- Python辦公自動(dòng)化SFTP詳解
相關(guān)文章
Python使用APScheduler實(shí)現(xiàn)定時(shí)任務(wù)過程解析
這篇文章主要介紹了Python使用APScheduler實(shí)現(xiàn)定時(shí)任務(wù)過程解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-09-09
跟老齊學(xué)Python之私有函數(shù)和專有方法
這篇文章是老齊學(xué)Python系列文章的一篇,主要介紹了跟私有函數(shù)和專有方法,需要的朋友可以參考下2014-10-10
深入理解Python虛擬機(jī)中列表(list)的實(shí)現(xiàn)原理及源碼剖析
Python使用re模塊實(shí)現(xiàn)okenizer(表達(dá)式分詞器)
在GitHub Pages上使用Pelican搭建博客的教程

