Python FTP processing

Source: Internet
Author: User

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


from pyftpdlib.authorizers import dummyauthorizerfrom pyftpdlib.handlers import  ftphandlerfrom pyftpdlib.servers import ftpserverfrom cfileoperator import  cfileoperatorimport ftplibimport osimport threadimport timeimport socketclass  Cftpserver ():     def __init__ (self, name= "song",  passwd= "song",  port= ):        self._name = name         self._passwd = passwd        self._port  = port    def start (self):         Authorizer = dummyauthorizer ()         authorizer.add_user ( self._name, self._passwd,  '. ',  perm= ' ELRADFMWM ')          authorizer.add_anonymouS (OS.GETCWD ())         handler = FTPHandler         handler.authorizer = authorizer         handler.banner =  "Pyftpdlib based ftpd ready."         address =  (",  self._port)          self._server = ftpserver (Address, handler)          self._server.max_cons = 256         self._server.max_cons_per_ip = 5        self._ Server.serve_forever ()     def stop (self):         self._server.close_all () class cftpclient ():     def __init__ (self,  Host= "127.0.0.1",  name= "song",  passwd= "song",  pOrt=21,savepath= './'):        self._host = host         self._name = name         self._passwd = passwd        self._port =  port        self._ftp = none         self._connet = false        self._buffer  = 2048        self._fileoperator = cfileoperator ( )         self._savepath=savepath         SELF._SRCPATH=OS.GETCWD ()     def conneterver (self):         try:            self . _ftp = ftplib. Ftp(self._host)         except  (Socket.error, socket.gaierror),  e:            print  ' Error: cannot  reach  "%s" '  % self._host             self._connet = False             return        print  ' *** connected to host   "%s" '  % self._host        try:             self._ftp.login (SELF._NAME, SELF._PASSWD)          except ftplib.error_perm:             print  ' error: login failed with  '%s '  and  '%s ' '  % self._name,&Nbsp;self._passwd            self._ftp.quit ()             self._connet = False             return         SELF._FTP.CWD ('./')         self._ftp.nlst ()          print  ' *** logged in '          self._connet = true    def cmdpath (Self,path):         if not self._connet:             self.conneterver ()         if not  self._connet:            return          self._ftp.cwd (path)     def getcur (self):         if not self._connet:             Self.conneterver ()         if not self._connet:             return         return self._ftp.pwd ()     def list (self):         if not self._connet:             self.conneterver ()         if not self._connet:             return         self._ftp.dir ()     def uploadfile (self, filename):         if not self._connet:             self.conneterver ()         if not self._connet:             return         elem = filename        if self._ Fileoperator.isdirexit (filename):             self. _fileoperator.tarfile (filename)             elem  +=  ". Tar"         file_open = open (elem,  ' RB ' )         self._ftp.storbinary (' stor %s '  %  Os.path.basename (Elem),  file_open, self._buffer)         if  not file_open.closed:  &nbsP;         file_open.close ()     def  Deleteromotefile (self,filename):         if not self._connet:             self.conneterver ()          if not self._connet:             return        self._ftp.delete (filename)      def deleteromotedir (Self,dir):        if  Not self._connet:            self.conneterver ()         if not self._connet:             RETURN        SELF._FTP.RMD ( Dir)   &NBSp; def renameromotefile (self,oldname,newname):         if  not self._connet:             Self.conneterver ()         if not self._connet:             return         self._ftp.rename (Oldname,newname)     def get_dirs_files (self):         dir_res = []        self . _ftp.dir ('. ',  dir_res.append)         files = [f.split ( NONE, 8) [ -1] for f in dir_res if f.startswith ('-')]         dirs = [f.split (none, 8) [-1] for f in dir_res  If f.startswith (' d ')]        return  (Files, dirs)     def  DownLoadFile (self, next_dir):         if not self._ Connet:            self.conneterver ()          if not self._connet:             return        print  ' walking  To ',  NEXT_DIR        SELF._FTP.CWD (next_dir)          try:             Os.mkdir (Next_dir)         except OSError:             pass        os.chdir ( Next_dir)          ftp_curr_dir = self._ftp.pwd ()          LOCAL_CURR_DIR = OS.GETCWD ()         files, dirs  = self.get_dirs_files ()         print  "files: ",  files        print  "dirs: ", dirs         for f in files:             print next_dir,  ': ', f             outf = open (f,  ' WB ')              try:                 self._ftp.retrbinary (' retr %s '  % f, outf.write)              finally:                 outf.close ()         for d in dirs:             os.chdir (Local_curr_dir)              SELF._FTP.CWD (Ftp_curr_dir)              self.walk (d) if __name__ ==  ' __main__ ':     c = cftpserver ()     thread.start_new_thread (C.Start,   ())     d = cftpclient ()     time.sleep (2)      d.uploadfile ("/home/test")     time.sleep      #d. UploadFile ("/home/test")   #  d.downloadfile ("/test.tar")     # f  =cfileoperator ()      #f. Tarfile ("/home/test") 


This article is from the "Wind Qing song" blog, please be sure to keep this source http://2309998.blog.51cto.com/2299998/1612687

Python FTP processing

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.