Python: Writing an FTP client using Ftplib

Source: Internet
Author: User
Tags ftp login ftp client

The Ftplib module in Python

The Ftplib module, which is installed by default in Python, defines the FTP class, where functions are limited and can be used to implement a simple FTP client for uploading or downloading files

FTP Workflow and basic operation can refer to protocol RFC959

FTP Login Connection

From ftplib import FTP #加载ftp模块

Ftp=ftp () #设置变量

Ftp.set_debuglevel (2) #打开调试级别2, show details

Ftp.connect ("IP", "Port") #连接的ftp Sever and ports

Ftp.login ("User", "password") #连接的用户名, 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-related command operations

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文件


You write the FTP download client, if you need to upload the client, please modify the next.

#!/usr/local/bin/python2.7# -*- coding: utf-8 -*-"uses Ftplib to write FTP client connections and to specify directory downloads. "' __author__ =  ' Linwangyi ' __date__ =" 2016-02-25 12:50 "Import ftplib ,socketfrom  sys import exitimport osclass doftp ():     def __init__ (self ):         #定义公用变量         self. Red_color= ' \033[1;31;48m '    #红  , configure the color         self of the terminal output. Blue_color= ' \033[1;34;48m '    #红  , configure the color         self of the terminal output. res= ' \033[0m '     def ftp_down (self,hostip,serport,ftpuser,ftppasswd,rootdir,server_ Files,local_dir):         myftp = ftplib. FTP ()         try:             myftp.connect (host=hostip,port=serport,timeout=5)             print  '%s** The "%s" Server FTP service has been successfully connected! %s '  %  (self. Blue_color,hostip,self. RES)         except  (Socket.error, socket.gaierror),  e:             print  '%s ' ERROR: Unable to access '%s '  ftp service, Please check! The error code is '%s '%s '  %  (self. Red_color,hostip,e,self. RES)             exit ()          try:             Myftp.login (USER=FTPUSER,PASSWD=FTPPASSWD)              print  '%s***** has successfully landed '%s ' Server FTP service! %s '  %  (self. Blue_color,hostip,self. RES)             print myftp.getwelcome () # Display FTP Server Welcome information         except  (ftplib.error_perm), e:             print  '%s Error: Login failed! , check that the username '%s ' password '%s ' is correct! The error code is '%s '%s '  %  (self. Red_color,ftpuser,ftppasswd,e,self. RES)             exit ()          MYFTP.CWD (rootdir)   #进入FTP目录         ftp_ Files = myftp.nlst ()     #取FTP当前目录内容         if  not Server_files:   #如果要下载为空, the entire contents of the catalog will be downloaded              DownLists = FTP_files             print  "ftp full directory%s"% downlists        else:              #判断指定下载的文件是否在FTP目录中.             downlists = []    #下载列表              NODownLists =[]   #没有下载列表             for line in server_ files:                if  line in ftp_files:                     downlists.append (line)                  else:                     nodownlists.append (line)              if NODownLists:                 print  "%s does not specify the file%s on the FTP server. %s '%  (self. Red_color, ",". Join (Nodownlists), self. RES)             if DownLists:                 print  "% S is downloading the following file%s from the FTP server. %s '%  (self. Blue_color, ",". Join (Downlists), self. RES)         bufsize = 1024         for line in DownLists:             filename = open (Local_dir + line, ' WB ') .write             myftp.retrbinary (' retr %s '  % os.path.basename ( Line), filename,bufsize)         myftp.quit ()          print  "%sftp has successfully exited. %s '%  (self. Blue_coLor,self. RES) if __name__ ==  "__main__":     hostip= ' XXXXX '    # FTP server IP or domain     serport= ' $ '        #FTP端口      ftpuser= ' Ftpuser '     #FTP用户     ftppasswd= ' XXXXXX '   #FTP对应用户密码     rootdir= '/test '     #FTP目录     server_files =  [' 1.txt ', ' 2.txt ', ' 3.txt ', ' 4.txt ']   #下载服务器文件列表      #Server_files  =  []  #如果要下载为空 will download the entire contents of the catalogue     local_dir = "d:/testtmp/downfile/"   # Local directory      #Local_files  =[' a.txt ', ' b.txt ']   #上传服务器本地文件列表      s = doftp ()     if os.path.exists (Local_dir) == False:   #判断本地是否有该文件目录, if not, will create         try:            &Nbsp;os.mkdir (local_dir)             print  "% s to create the local directory '%s '%s '%  (s.blue_color,local_dir,s.res)         except:             print  "%s Cannot create local directory '%s ', The reason is that there is no such drive or directory path problem, the program directly quit! %s "%  (s.red_color,local_dir,s.res)              exit ()   #退出程序     s.ftp_down (hostip,serport,ftpuser,ftppasswd,rootdir,server_ Files,local_dir)


The results of the implementation are as follows:

650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M02/7C/1B/wKioL1bOu93R-0CmAAApC5cMQfo947.png "title=" 1.png " alt= "Wkiol1bou93r-0cmaaapc5cmqfo947.png"/>

This article is from the "Urban Cloth" blog, please be sure to keep this source http://sunday208.blog.51cto.com/377871/1745041

Python: Writing an FTP client using Ftplib

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.