python多目录字符串查找匹配
1. 需求来自于实际工作: 需要处理一批服务器上运行的redis实例,每个redis实例可能有密码,也可能没有,有密码的,密码配置格式一定是: requirepass XXXXX # XXXX是密码
2. 这些配置文件来自于各个某个目录下的各个子目录,因此,需要对这些目录进行递归查找
3. 凡是该配置文件,一定以conf结尾作为文件名
1 #coding:utf-8 2 3 import re 4 import os 5 6 7 # pConf = re.compile(r'redis-|redis') 8 pConf = re.compile(r'conf') 9 pPassWord = re.compile(r'requirepass') 10 11 upstreamFilesList = list() 12 confFilesList = list() 13 14 15 def getFileList(entry): 16 for root, dirs, files in os.walk(entry): 17 for file in files: 18 if re.search(pConf, file.strip('\n')): 19 fileAbsPath = os.path.join(root, file) 20 confFilesList.append(fileAbsPath) 21 else: 22 print 'not conf', file 23 return confFilesList 24 25 26 def getRedisAuth(filepath): 27 findFlag = False 28 with open(filepath + '' , 'r') as fd: 29 while True: 30 line = fd.readline() 31 if line: 32 if re.findall(pPassWord, line.strip('\n')): 33 findFlag = True 34 print filepath, line.strip('\n').strip() 35 else: 36 break 37 if not findFlag: 38 print filepath ,'nopassword' 39 40 41 if __name__ == '__main__': 42 with open('redis_single_ip.txt', 'r') as fd: 43 while True: 44 ip = fd.readline().strip('\n') 45 if ip: 46 getFileList(ip) 47 else: 48 break 49 for confFile in confFilesList: 50 getRedisAuth(confFile)

浙公网安备 33010602011771号