`

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

 
阅读更多

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`是这个脚本的核心,它使用批处理语言...

    登陆脚本(输入用户名、密码).txt

    该程序为wincc自定义界面的登陆脚本,希望能够帮助到大家。

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

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

    最新 Microsoft Edge 一键卸载脚本

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

    3dmax一键灯带脚本插件

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

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

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

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

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

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

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

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

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

    cacti1.2.16 一键安装脚本

    cacti1.2.16 一键安装脚本

    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; 将脚本和以上三个安装包拷贝至/...

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

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

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

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

    nginx一键安装包含自动安装脚本

    这个脚本会自动执行下载、解压、配置、编译和安装等一系列操作,大大减少了手动操作的繁琐。脚本通常包含以下功能: 1. **检查依赖**: 检查系统是否已经安装了所需的库,如果没有,自动下载并安装。 2. **设置变量...

    mstsc远程登录一键自动登录脚本

    按装autoIt,修改脚本对应的参数,IP、用户名、密码,自动完成输入。登录远程计算机。

    hadoop全分布式-脚本一键安装

    你需要将所有必要的文件,包括Hadoop的配置文件(如core-site.xml、hdfs-site.xml、yarn-site.xml、mapred-site.xml等)、自定义的安装脚本,以及已经下载的JDK和Hadoop软件包,放置在同一个目录下。JDK和Hadoop的...

    XRDP一键安装脚本(支持多个ubuntu版本)

    在远程连接时,用户需要知道服务器的IP地址或域名,并可能需要输入用户名和密码。对于安全起见,推荐使用SSH隧道加密连接,或者配置SSL证书以增强连接安全性。 总的来说,XRDP一键安装脚本简化了在Ubuntu系统上设置...

    Centos7下Python3.6.6一键安装脚本及相关包

    5. 安装Python:将编译后的Python二进制文件复制到系统路径,如/usr/local/bin。 6. 安装pip:通过Python的get-pip.py脚本获取并安装pip。 7. 安装virtualenv:利用pip安装virtualenv。 8. 验证安装:检查Python ...

Global site tag (gtag.js) - Google Analytics