Encountered a problem, need to match the file in the remote FTP directory, if you can use an FTP client to do this easily by using the command line, but there is no tool to support such a requirement, then with Python support for FTP and support for regular expressions, write a simple tool A file that uses regular expressions to match a remote directory.
The code is as follows
# coding=utf-8 ######################################################################### # File Name:reg_url.py #
Author:wangweilong # Company:baidu ######################################################################### Import RE import sys import OS from ftplib import FTP dhccmd = "Http://xxx/api/submit" Class Dhc_ftp (): Def __init__ (SE LF, hostname, username= "", Passwd= ""): Self.hostname = hostname try:self.ftp = FTP (self.hostname) except:pri
NT "hostname error!" Exit ( -1) Self.username = Username SELF.PASSWD = passwd self.filelist = [] Self.reg_pattern = "" Def Getftpfileli St (Self, Path): Self.ftp.login (Self.username, self.passwd) self.ftp.cwd (path) self.filelist = Self.ftp.nlst () def Matchnames (self, regpattern): pattern = Re.compile (regpattern) matchedfiles = [] for file in Self.filelist:match = Pattern.search (file) if Match:matchedfiles.append (match.string) return matchedfiles if __name__ = "__main __ ": If Len (sys. argv)!= 4:print ' Usage:python reg_url.py $ftpurldir $regular ' else: #解析ftpurl字符串 head = Sys.argv[1].split ("@") [1 ].split ("/") [0] username = sys.argv[1].split ("//") [1].split (":") [0] passwd = sys.argv[1].split ("//") [1].split (":") [1 ].split ("@") [0] Pathdir = sys.argv[1].split (head) [1] dhc_ftp = dhc_ftp (head, username, passwd) Dhc_ftp.getftpfileli St ("./" + pathdir) #获取正则表达式 Regpattern = R '%s '% sys.argv[2] matchedfiles = Dhc_ftp.matchnames (Regpattern) for F
Iles in matchedfiles:ftpname = sys.argv[1] + "/" + Files print Ftpname
By entering the remote directory address you want to retrieve and the regular expression you want to match, you can get to the far end of the file, as to what to do with these files, that is the demand problem.
The above mentioned is the entire content of this article, I hope you can enjoy.
Please take a moment to share the article with your friends or leave a comment. We will sincerely thank you for your support!