python implements the method of downloading the entire ftp directory

  • 2020-05-24 05:48:17
  • OfStack

preface

Recently because of business needs, wrote the script, the script task from FTP downloaded a directory, download a file from the FTP is known to all the available with get command, download multiple files can use mget, but you need to download a directory, I'm sorry, can't, if don't want to compete, you said use lftp, then use mirror command can also ah, this I do not seriously, because every company has each scene, choosing the appropriate line, because we this FTP is done with ssl, so lftp can't use it, The basic idea of the script is to set up an ftp connection, then log in to get the list of files, and according to the returned list, go through the for loop and download one by one.

The script is as follows:


#!/usr/bin/evn python
 
from ftplib import FTP_TLS, FTP
import socket
import ssl
import os
import sys
 
class IMPLICIT_FTP_TLS(FTP_TLS):
 # The constructor initializes the parent class 
 def __init__(self, host='', user='', passwd='', acct='', keyfile=None,
  certfile=None, timeout=60):
  FTP_TLS.__init__(self, host, user, passwd, acct, keyfile, certfile, timeout)
 # Server setup FTPS The connection 
 def connect(self, host='', port=0, timeout=-999):
  if host != '':
   self.host = host
  if port > 0:
   self.port = port
  if timeout != -999:
   self.timeout = timeout
  try:
   # create socket
   self.sock = socket.create_connection((self.host, self.port), self.timeout)
   self.af = self.sock.family
   #wrap_socket receive 1 a socket The instance , return SSLSocket Examples can be understood in ordinary socket Encapsulates the on 1 layer ssl
   self.sock = ssl.wrap_socket(self.sock, self.keyfile, self.certfile)
   self.file = self.sock.makefile('rb')
   self.welcome = self.getresp()
  except Exception as e:
   print (e)
  return self.welcome
 
 
def get_ftp_ver(version):
 # If you don't have it, create a new directory 
 if not os.path.isdir(version):
  os.makedirs(version)
 ftps = IMPLICIT_FTP_TLS()
 ftps.connect(host='10.0.0.8', port=666)
 ftps.login(user="ftp_user", passwd="ftp_password")
 # A secure data connection is established before data can be returned. 
 ftps.prot_p()
 ftps.cwd(version)
 files = ftps.nlst()
 # Go to the local directory 
 os.chdir(version)
 # Download each file in a loop 
 for file in files:
  fp = open(file, 'wb')
  ftps.retrbinary('RETR %s' % file, fp.write)
 ftps.close()
 
if __name__ == '__main__':
 get_ftp_ver(sys.argv[1])

Script usage:


#python get_data.py version_20160920

The next parameter is basically the name of the file that you want to update, and then you run it and you can download the entire directory, and you can see the rest of the script in the comments.

The above is the whole content of this article, I hope the content of this article to your study or work can bring 1 definite help, if you have questions you can leave a message to communicate.


Related articles: