python多目录字符串查找匹配

时间:2023-12-23 11:25:14

1. 需求来自于实际工作: 需要处理一批服务器上运行的redis实例,每个redis实例可能有密码,也可能没有,有密码的,密码配置格式一定是: requirepass XXXXX # XXXX是密码

2. 这些配置文件来自于各个某个目录下的各个子目录,因此,需要对这些目录进行递归查找

3. 凡是该配置文件,一定以conf结尾作为文件名

#coding:utf-8

import re
import os # pConf = re.compile(r'redis-|redis')
pConf = re.compile(r'conf')
pPassWord = re.compile(r'requirepass') upstreamFilesList = list()
confFilesList = list() def getFileList(entry):
for root, dirs, files in os.walk(entry):
for file in files:
if re.search(pConf, file.strip('\n')):
fileAbsPath = os.path.join(root, file)
confFilesList.append(fileAbsPath)
else:
print 'not conf', file
return confFilesList def getRedisAuth(filepath):
findFlag = False
with open(filepath + '' , 'r') as fd:
while True:
line = fd.readline()
if line:
if re.findall(pPassWord, line.strip('\n')):
findFlag = True
print filepath, line.strip('\n').strip()
else:
break
if not findFlag:
print filepath ,'nopassword' if __name__ == '__main__':
with open('redis_single_ip.txt', 'r') as fd:
while True:
ip = fd.readline().strip('\n')
if ip:
getFileList(ip)
else:
break
for confFile in confFilesList:
getRedisAuth(confFile)