python ftplib模塊


函數釋義

Python中默認安裝的ftplib模塊定義了FTP類,其中函數有限,可用來實現簡單的ftp客戶端,用於上傳或下載文件,函數列舉如下

ftp登陸連接
from ftplib import FTP            #加載ftp模塊
ftp=FTP()                         #設置變量
ftp.set_debuglevel(2)             #打開調試級別2,顯示詳細信息
ftp.connect("IP","port")          #連接的ftp sever和端口
ftp.login("user","password")      #連接的用戶名,密碼
print ftp.getwelcome()            #打印出歡迎信息
ftp.cmd("xxx/xxx")                #進入遠程目錄
bufsize=1024                      #設置的緩沖區大小
filename="filename.txt"           #需要下載的文件
file_handle=open(filename,"wb").write #以寫模式在本地打開文件
ftp.retrbinaly("RETR filename.txt",file_handle,bufsize) #接收服務器上文件並寫入本地文件
ftp.set_debuglevel(0)             #關閉調試模式
ftp.quit()                        #退出ftp

ftp相關命令操作
ftp.cwd(pathname)                 #設置FTP當前操作的路徑
ftp.dir()                         #顯示目錄下所有目錄信息
ftp.nlst()                        #獲取目錄下的文件
ftp.mkd(pathname)                 #新建遠程目錄
ftp.pwd()                         #返回當前所在位置
ftp.rmd(dirname)                  #刪除遠程目錄
ftp.delete(filename)              #刪除遠程文件
ftp.rename(fromname, toname)#將fromname修改名稱為toname。
ftp.storbinaly("STOR filename.txt",file_handel,bufsize)  #上傳目標文件
ftp.retrbinary("RETR filename.txt",file_handel,bufsize)  #下載FTP文件

FTP.quit()與FTP.close()的區別

  • FTP.quit():發送QUIT命令給服務器並關閉掉連接。這是一個比較“緩和”的關閉連接方式,但是如果服務器對QUIT命令返回錯誤時,會拋出異常。
  • FTP.close():單方面的關閉掉連接,不應該用在已經關閉的連接之后,例如不應用在FTP.quit()之后。

例1:下載、上傳文件

#coding: utf-8
from ftplib import FTP
import time
import tarfile
#!/usr/bin/python
#-*- coding: utf-8 -*-

from ftplib import FTP

def ftpconnect(host, username, password):
    ftp = FTP()
    #ftp.set_debuglevel(2)         #打開調試級別2,顯示詳細信息
    ftp.connect(host, 21)          #連接
    ftp.login(username, password)  #登錄,如果匿名登錄則用空串代替即可
    return ftp
    
def downloadfile(ftp, remotepath, localpath):
    bufsize = 1024                #設置緩沖塊大小
    fp = open(localpath,'wb')     #以寫模式在本地打開文件
    ftp.retrbinary('RETR ' + remotepath, fp.write, bufsize) #接收服務器上文件並寫入本地文件
    ftp.set_debuglevel(0)         #關閉調試
    fp.close()                    #關閉文件

def uploadfile(ftp, remotepath, localpath):
    bufsize = 1024
    fp = open(localpath, 'rb')
    ftp.storbinary('STOR '+ remotepath , fp, bufsize) #上傳文件
    ftp.set_debuglevel(0)
    fp.close()                                    

if __name__ == "__main__":
    ftp = ftpconnect("******", "***", "***")
    downloadfile(ftp, "***", "***")
    uploadfile(ftp, "***", "***")

    ftp.quit()

例2:上傳、下載文件/目錄

#coding:utf-8
from ctypes import *
import os
import sys
import ftplib

class myFtp:
    ftp = ftplib.FTP()
    bIsDir = False
    path = ""
    def __init__(self, host, port='21'):
        #self.ftp.set_debuglevel(2) #打開調試級別2,顯示詳細信息 
        #self.ftp.set_pasv(0)      #0主動模式 1 #被動模式
        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' )
        self.ftp.retrbinary( "RETR %s" %( RemoteFile ), file_handler.write ) 
        file_handler.close()
        return True
    
    def UpLoadFile(self, LocalFile, RemoteFile):
        if os.path.isfile( LocalFile ) == False:
            return False
        file_handler = open(LocalFile, "rb")
        self.ftp.storbinary('STOR %s'%RemoteFile, file_handler, 4096)
        file_handler.close()
        return True

    def UpLoadFileTree(self, LocalDir, RemoteDir):
        if os.path.isdir(LocalDir) == False:
            return False
        print "LocalDir:", LocalDir
        LocalNames = os.listdir(LocalDir)
        print "list:", LocalNames
        print RemoteDir
        self.ftp.cwd( RemoteDir )
        for Local in LocalNames:
            src = os.path.join( LocalDir, Local)
            if os.path.isdir( src ): self.UpLoadFileTree( src, Local )
            else:
                self.UpLoadFile( src, Local )
                
        self.ftp.cwd( ".." )
        return
    
    def DownLoadFileTree(self, LocalDir, RemoteDir):
        print "remoteDir:", RemoteDir
        if os.path.isdir( LocalDir ) == False:
            os.makedirs( LocalDir )
        self.ftp.cwd( RemoteDir )
        RemoteNames = self.ftp.nlst()  
        print "RemoteNames", RemoteNames
        print self.ftp.nlst("/del1")
        for file in RemoteNames:
            Local = os.path.join( LocalDir, file )
            if self.isDir( file ):
                self.DownLoadFileTree( Local, file )                
            else:
                self.DownLoadFile( Local, file )
        self.ftp.cwd( ".." )
        return
    
    def show(self, list):
        result = list.lower().split( " " )
        if self.path in result and "<dir>" in result:
            self.bIsDir = True
     
    def isDir(self, path):
        self.bIsDir = False
        self.path = path
        #this ues callback function ,that will change bIsDir value
        self.ftp.retrlines( 'LIST', self.show )
        return self.bIsDir
    
    def close(self):
        self.ftp.quit()

if __name__ == "__main__":
    ftp = myFtp('*****')
    ftp.Login('***','***')

    ftp.DownLoadFileTree('del', '/del1')#ok
    ftp.UpLoadFileTree('del', "/del1" )
    ftp.close()
    print "ok!"

:目錄內為文件,若為目錄則無法傳輸

例3:異常處理

#coding: utf-8
#from ftplib import FTP
import ftplib
import socket
import os

def ftpconnect(ftp_info):
    try:
        ftp = ftplib.FTP(ftp_info[0])
    except (socket.error, socket.gaierror):
        print "ERROR: cannot reach %s" % ftp_info[0]
        return None

    username = ftp_info[1]
    passwd = ftp_info[2]
    try:
        ftp.login(username, passwd)
    except ftplib.error_perm:
        print "ERROR: cannot login anonymously"
        ftp.quit()
        return None
    return ftp

if __name__ == "__main__":
    info_list = ["10.19.3.199", "fastupdate_amap", "@utonavi&A.map"]
    ftp = ftpconnect(info_list)
    if not ftp:
        exit(1)
    bufsize = 1024
    fname = "20150416113942674.tar.gz"
    fp = open(os.path.join(".", fname), 'wb')
    remotefile = os.path.join("/ADF++", fname)
    ftp.retrbinary("RETR " + remotefile, fp.write, bufsize)

    #是否有目錄,沒有就創建;有的話看是否有權限創建
    a = ftp.dir()
    try:
        ftp.cwd("jimi")
    except ftplib.error_perm:
        try:
            ftp.mkd("jimi")
        except ftplib.error_perm:
            print "WARNING: U have no authority to make dir"
    finally:
        ftp.quit()

ftp例子參考鏈接

http://www.example-code.com/python/ftp.asp


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM