This python script will connect to a designated FTP server. Obtain a list of all files, then sort all files with a .jpa extension and then download the latest one.
In order to do this regular expressions are used to build a list of files only containing .jpa file extensions. This list is then sorted by each of the integers contained within each file name.
#!/usr/bin/python # # Usage : Download latest .jpa file from FTP Server. import ftplib ## IMPORT MODULES import string ## IMPORT MODULES import os ## IMPORT MODULES import re ## IMPORT MODULES ftpserver = "ftp.server" ## ASSIGN VARIABLE username = "username" ## ASSIGN VARIABLE password = "password" ## ASSIGN VARIABLE localdir = "/path/example" ## ASSIGN VARIABLE data = [] ## SET EMPTY LIST list2 = [] ## SET EMPTY LIST os.chdir(localdir) ## CHANGE LOCAL DIRECTORY ftp = ftplib.FTP(ftpserver) ## SET FTPLIB MODULE TO FTPSERVER + ASSIGN TO FTP try: ftp.login(username, password) ## LOG INTO FTP SERVER ftp.dir(data.append) ## GET DIRECTORY LISTING + ASSIGN TO LIST ## CONVERT DIR LISTING LINES TO WORDS FOR EACH ELEMENT data = " ".join(data) ## CONVERT DATA LIST INTO STR data = data.split() ## CONVERT DATA STR INTO LIST y = re.compile('.*\.jpa$') ## SET REGEX MATCH CRITERIA for x in data: ## LOOP THROUGH DATA LIST + APPEND ... if y.match(x): ## ... ANY ELEMENT MATCHING REGEX TO LIST2. list2.append(x) dstfile = (' '.join(sorted(list2, key = lambda x:x[-19:-4]))) ## SORT LIST2 BY NUMERIC DIGITS WITHIN ELEMENTS + ASSIGN TO STR dstfile = dstfile.split() ## SPLIT STR TO LIST dstfile = dstfile[-1] ## ASSIGN LAST ELEMENT OF LIST TO STR ftp.retrbinary('RETR '+dstfile, open(dstfile, 'wb').write) ## GET FILE ftp.close() ## CLOSE FTP CONNECTION GRACEFULLY except Exception, e: print e
Latest posts by Rick Donato (see all)
- How to Configure a BIND Server on Ubuntu - March 15, 2018
- What is a BGP Confederation? - March 6, 2018
- Cisco – What is BGP ORF (Outbound Route Filtering)? - March 5, 2018
Want to become a programming expert?
Here is our hand-picked selection of the best courses you can find online:
Python Zero to Hero course
Python Pro Bootcamp
Bash Scripting and Shell Programming course
Automate with Shell Scripting course
The Complete Web Development Bootcamp course
and our recommended certification practice exams:
AlphaPrep Practice Tests - Free Trial