`

一键执行脚本即可把用户名和密码更新到指定路径下相应的配置文件(支持迭代)

 
阅读更多

1) 数据库和相关应用的用户名, 密码等敏感信息加密之后集中存放在某一文件

2) Production Service 只需一键执行脚本即可把用户名和密码更新到指定路径下相应的配置文件(支持迭代).

 

#!/usr/bin/env python
import os
import sys
import re

# To read from credential file and put key/value pairs into a map
def getCredentialMap(credentialFile):
	credentialsMap={}
	f = open(credentialFile, 'r')
	for line in f.readlines():
		if not line.startswith('#'):
			tokens = line.split('=')
			credentialsMap['${' + tokens[0].strip() + '}'] = tokens[1].strip()
	return credentialsMap

# To scan recursively from a specific top folder where there are configuration files need to update their credentials
def scan(path, map, extensions, log):
	for i in os.walk(path):
		dirpath=i[0]
		dirnames=i[1]
		filenames=i[2]
		for j in filenames:
			processFile(os.path.join(dirpath, j), map, extensions, log)
		for k in dirnames:
			scan(os.path.join(dirpath, k), map, extensions, log)

# To process a specific file		
def processFile(pathfile, map, extensions, log):
	extension = os.path.splitext(pathfile)[1]
	if extension not in extensions:
		return
	else:
		fh = open(pathfile, 'r+')
		newFile = ''
		updated = False
		lineNo = 0
		for line in fh.readlines():
			lineNo += 1
			replaced, text = processLine(line, map)
			if replaced:
				updated = True
				log.write(pathfile + os.linesep)
				log.write('Line %3d: %s' % (lineNo, line.rstrip()) + os.linesep)
				log.write('========> %s' % (text.rstrip()) + os.linesep)
			newFile = newFile + text
		fh.close()	
		if updated:
			fh = open(pathfile, 'r+')
			fh.truncate()
			fh.write(newFile)
			fh.close()

# To process a specific line
def processLine(line, map):
	text = line
	pattern = r'\${.+?}' 
	replaced = False
	for match in re.finditer(pattern, line):
		s = match.start()
		e = match.end()
		key = line[s:e]
		value = map[key]
		if value:
			text = line.replace(key, value)
			replaced = True
	return (replaced, text)

# The entry of this program	
def main():
		
	sampleFile='''
	#-----Follows are the content of a sample configuration file-----
	#path to the credentials file
	ssts.credentials.path=./credentials.properties
	#path(s) to the target top foder(s). Please separate with ";" when there is more than one target top folder
	ssts.target.path=./config;./build
	#the extentions of configuration files
	file.extention.filter=.xml;.properties
	#---------------------------------------------------------------
	'''
	configFile = os.path.splitext(sys.argv[0])[0] + '.properties'
	logFile = os.path.splitext(sys.argv[0])[0] + '.log'
	log = open(logFile, 'w')
	log.truncate()
	map = {}
	targetPath = []
	try:

		fh = open(configFile, 'r')
		for line in fh.readlines():
			if line.startswith('ssts.credentials.path'):
				credentialFile=line.split('=')[1].strip()
			if line.startswith('ssts.target.path'):
				targetPath=line.split('=')[1].strip().split(';')
			if line.startswith('file.extension.filter'):
				extensions=line.split('=')[1].strip().split(';')
		map = getCredentialMap(credentialFile)
	except IOError, e:
		print 'Please prepare ' + configFile + ' with this script ' + sys.argv[0],
		print sampleFile
		print e
	except Exception, e:
		print e
	
	for path in targetPath:
		scan(path, map, extensions, log)
	log.close()

if __name__ == '__main__':
	main()

 

Groovy version:

#!/usr/bin/env groovy

// To read from credential file and put key/value pairs into a map
def getCredentialMap(String credentialFile){
	credentialsMap=[:]
	def f = new File(credentialFile)
	f.eachLine{
		if(!it.startsWith('#')){
			def tokens = it.split('=')
			credentialsMap.put('${'+tokens[0].trim()+'}', tokens[1].trim())
		}
	}
	return credentialsMap
}	

// To scan recursively from a specific top folder where there are configuration files need to update their credentials
def scan(path, map, extensions, log){
	new File(path).eachFileRecurse {
		if(it.isFile()){
			processFile(it, map, extensions, log)
		}
	}
}

// To process a specific file		
def processFile(file, map, extensions, log){
	def extension = '.' + file.getName().split(/\./)[1]
	if(extension in extensions){
		def newFile = new StringBuilder()
		def updated = false
		def lineNo = 0
		file.eachLine{
			lineNo += 1
			def result = processLine(it, map)
			def replaced = result[0] 
			def text = result[1]
			if(replaced){
				updated = true
				log.append(file.getCanonicalFile().toString() + System.getProperty('line.separator'))
				log.append(String.format('Line %3d: %s', lineNo, it.trim()) + System.getProperty('line.separator'))
				log.append(String.format('========> %s', text.trim()) + System.getProperty('line.separator'))
			}
			newFile.append(text)
		}
		if(updated){
			file.write('')
			file.write(newFile.toString())
		}
	}
}

// To process a specific line
def processLine(line, map){
	def text = line
	def pattern =  ~/\$\{.+?\}/
	def replaced = false
	def matcher = pattern.matcher(line)
	def count = matcher.getCount()
	for(i in 0..<count){
		def key = matcher[i]
		def value = map.get(key)
		if( value != null){
			text = line.replace(key, value)
			replaced = true
		}
	}
	text = text + System.getProperty('line.separator')
	return [replaced, text]
}	
def void MAIN(){ 
	def sampleFile='''
#-----Follows are the content of a sample configuration file-----
#path to the credentials file. (Don't input any space in between)
suez.credentials.path=./ssts-credentials.properties
#path(s) to the target top foder(s). Please separate with ";" when there is more than one target top folder. (Don't input any space in between)
suez.target.path=./config;./build
#the extentions of configuration files. (Don't input any space in between)
file.extention.filter=.xml;.properties;.cfg
#----------------------------------------------------------------
	'''
	
	def configFile = this.class.name + '.properties'
	def logFile = this.class.name + '.log'
	def log = new File(logFile)
	log.write('')
	def map = [:]
	def credentialFile
	def targetPath = []
	def extensions = []
	
		try{	
			new File(configFile).eachLine{
				if(it.startsWith('suez.credentials.path'))
					credentialFile=it.split('=')[1].trim()
				if(it.startsWith('suez.target.path'))
					targetPath=it.split('=')[1].trim().split(';')
				if(it.startsWith('file.extension.filter'))
					extensions=it.split('=')[1].trim().split(';')
					
			}
			map = getCredentialMap(credentialFile)
		}catch(IOException e){
			println 'Please prepare ' + configFile + ' for this script ' + this.class.name + '.groovy'
			println sampleFile
			println e
		}catch(Exception e){
			println e
		}
		
		for(path in targetPath){
			scan(path, map, extensions, log)
		}
	}

MAIN()

 

分享到:
评论

相关推荐

    BAT批处理脚本-获取当前用户名和密码.zip

    总的来说,"BAT批处理脚本-获取当前用户名和密码.zip"这个压缩包文件提供了一个获取当前活动用户名的示例,但获取密码的功能在Windows批处理脚本中并不直接可行。这提醒我们在使用自动化工具时,应充分理解其功能...

    Windows Server 密码永不过期一键优化脚本

    这一功能的实现主要涉及到本地安全策略(Local Security Policy)的修改,尤其是密码策略中的“密码必须满足复杂性要求”和“密码最长使用期限”这两项设置。 `noOverdue.bat`是这个脚本的核心,它使用批处理语言...

    mysql8.0 附带一键安装脚本

    MySQL 8.0 是 MySQL 数据库管理系统的最新版本,提供了许多增强的功能和性能优化,旨在为开发者和企业级用户提供更高效、安全的数据存储和管理体验。这个“mysql8.0 附带一键安装脚本”可能包含了一个简化 MySQL 8.0...

    3dmax一键灯带脚本插件

    《3Dmax一键灯带脚本插件详解与应用》 在三维建模与渲染的世界里,3Dmax是一款广泛使用的强大工具,尤其在建筑设计、室内设计和游戏制作等领域。而“3dmax一键灯带脚本插件”是3Dmax用户们的一款得力助手,它极大地...

    windows上一键安装mysql的bat脚本(实测)

    3. **配置参数**:脚本会读取`conf.properties`文件中的配置信息,如端口号、用户名、密码等,以便在安装过程中设置MySQL服务器的参数。 4. **启动服务**:安装完成后,脚本可能还会启动MySQL服务,确保数据库能正常...

    最新 Microsoft Edge 一键卸载脚本

    3. **解除关联与清理**:脚本会找到与Microsoft Edge相关的注册表键和配置文件,并逐一删除,确保彻底卸载。这包括删除启动项、清除缓存、卸载更新等。 4. **重启相关服务**:为了确保所有更改生效,脚本可能还会...

    ZABBIX一键安装脚本_zabbix-install-linux.zip

    为了解决这个问题,社区和一些公司提供了各种一键安装脚本,这些脚本将安装和配置过程自动化,从而大大降低了部署Zabbix的门槛。这些脚本通常会包含安装所有必要的依赖项、下载Zabbix的源代码、配置数据库、设置Web...

    fas_fas流控_fas一键脚本_fas自启脚本_fas免流脚本_fas搭建脚本_

    这种脚本通常包含了所有必要的命令和配置文件,用户只需运行一个命令即可完成整个FAS系统的部署。它极大地降低了系统部署的复杂性,使得非专业人员也能快速上手,提高了工作效率。 ** fas自启脚本** fas自启脚本是...

    linux-linux各类一键安装脚本懒人用懒办法

    在Linux世界中,为了提升效率,开发者们常常编写一键安装脚本来快速配置环境或安装软件。"linux-linux各类一键安装脚本懒人用懒办法"这个主题正体现了这一实践,它旨在帮助用户节省时间,避免繁琐的手动配置过程。...

    cacti1.2.16 一键安装脚本

    cacti1.2.16 一键安装脚本

    BBR一键安装脚本_原作者_httpsgithub.comchiakgeLinux-Ne_Linux-NetSpeed.zip

    2. 安装脚本:实际执行安装的脚本文件,它可能包含各种命令来更新系统、安装必要的软件包、下载和编译内核模块等。 3. 配置文件:用于配置网络参数,确保BBR算法能够在系统中正确启用。 4. 卸载脚本:用于在需要时...

    BAT批处理脚本-加密解密-开通局域网共享(访问本机要填用户名和密码).zip

    标题中的"BAT批处理脚本-加密解密-开通局域网共享(访问本机要填用户名和密码).zip"表明这是一个包含批处理脚本的压缩文件,主要功能涉及文件的加密解密以及设置局域网共享,其中在访问共享资源时需要输入用户名和...

    黑域一键开启脚本和安卓工具

    "一键开启脚本"的作用在于,通过运行特定的脚本命令,自动完成黑域的启动和配置。这包括但不限于开启黑域服务、设置必要的权限、配置应用冻结规则等。使用这样的工具,非技术背景的用户也能轻松管理他们的手机性能,...

    openssh-9.8p1一键升级脚本

    这种脚本通常会自动处理依赖关系、配置文件的备份和恢复等问题,确保更新过程平滑无误。 5. 脚本的执行与管理:在执行一键升级脚本之前,系统管理员需要确保对脚本有足够的了解,了解其操作步骤和潜在的影响。通常...

    Centos7安装mongodb一键执行脚本

    Centos7安装mongodb一键执行脚本,适用于以下版本: mongodb-linux-x86_64-rhel70-4.4.20.tgz; mongodb-linux-x86_64-rhel70-5.0.16.tgz; mongodb-linux-x86_64-rhel70-6.0.5.tgz; 将脚本和以上三个安装包拷贝至/...

    萌咖大佬的Linux 一键DD脚本项目资源.zip

    脚本编程作为实现自动化的关键技术之一,能够在Linux环境下执行一系列命令,完成复杂的任务配置和管理。 在众多的Linux脚本工具中,DD(Data Dumper)工具是一个常用的磁盘镜像工具,它可以用于创建、转换和恢复...

    大数据环境一键安装脚本.zip

    "大数据环境一键安装脚本.zip" 提供了一种自动化的方式来设置和配置大数据环境,极大地简化了传统手动安装过程中的复杂性。这个压缩包文件"automaticDeploy-master"很可能是包含了一个完整的自动化部署项目,下面将...

    ELK日志分析平台一键部署脚本

    ELK日志分析平台一键部署脚本 架构:logstash+elasticsearch+kibana 功能:shell脚本一键部署 亲测有用!!!

    oracle11g一键安装脚本

    oracle11g centos7一键安装脚本,脚本里面有完整安装提示说明。大概步骤如下 1、关闭防火墙 2、设置服务器名称并增加映射 3、安装Oracle所需的依赖 4、解压oracle安装包 5、创建用户和组 6、修改内核参数 7、修改用户...

Global site tag (gtag.js) - Google Analytics