Shell脚本实现批量生成nagios配置文件
如果管理的站点和服务器较多的情况下,每次修改配置文件都相当痛苦。因而想到了用shell脚本来批量生成配置文件和配置数据。下面这个脚本是为了批量生成nagios监控配置文件的一个shell脚本程序。其原理是事先定义一个shell脚本模板,然后每个需要监控的站点复制一份模板替换掉模板文件里面的变量。
1、准备模板文件webcheck.template
morewebcheck.template
###################WEBURLdefinestart###################
defineservice{
usegeneric-service;Nameofservicetemplatetouse
host_namewebcheck
service_descriptionWEBURL
check_commandcheck_webpage!-HWEBURL-uINDEX
is_volatile0
max_check_attempts3
check_interval1
retry_interval1
check_period24x7
notification_interval5
notification_period24x7
notification_optionsw,u,r,c
contact_groupsadmins
}
###################WEBURLdefineend###################
变量为WEBURL和INDEX
2、站点列表文件weblist.txt
www.aaa.com\\/ bbs.bbb.com\\/ www.ccc.com\\/
weblist.txt有两个field,第一个field为域名,第二个field为站点对应的url。如第一个域名为www.aaa.com/
3、批量生成脚本文件create.sh
[root@bogonwebcheckes]#morecreate.sh
#!/bin/bash
PATH=/bin:$PATH:$HOME/bin:/sbin:/usr/bin:/usr/sbin
exportPATH
#echo$PATH
usage(){
echo-en"USAGE:$0[weblist]or$0[template][weblist]\nForexample:$0host.templatehost.list(Field:[WEBURL][INDEXWEBPAGE])\n"1>&2
exit1
}
if[$#-gt2];then
usage
exit1
fi
case"$#"in
2)
template=$1
host_list=$2
;;
1)
template='webcheck.template'
host_list=$1
;;
0)
#template='webcheck.template'
#host_list='host.list'
usage
;;
esac
if[!-f"${template}"];then
echo"template:${template}notexist!"1>&2
exit1
fi
if[!-f"${host_list}"];then
echo"hostlist:${host_list}notexist!"1>&2
exit1
fi
#echo$PWD/${host_list}
WEBTEMP="wcalltemp.txt"
rm$PWD/${WEBTEMP}
#cat$PWD/${host_list}
/bin/cat$PWD/${host_list}|
whilereadweburlindex
do
#echo"${ip}"|grep-oP'^\d{1,3}(\.\d{1,3}){3}$'>/dev/null2>&1||Field='notip'
#if["${Field}"='notip'];then
#echo"${ip}notip!"1>&2
#exit1
#fi
#host_cfg="${hostname}-${ip}.cfg"
tmppage="webtemp.txt"
cp${template}${tmppage}
sed-i"s/WEBURL/${weburl}/g;s/INDEX/${index}/g"${tmppage}
/bin/cat${tmppage}>>${WEBTEMP}
done
/bin/catwebcheck_org.template>webcheck_${host_list}.cfg
/bin/cat${WEBTEMP}>>webcheck_${host_list}.cfg
rm$PWD/${WEBTEMP}
/usr/local/nagios/bin/nagios-v/usr/local/nagios/etc/nagios.cfg
servicenagiosrestart
起作用的主要是这句,sed-i"s/WEBURL/${weburl}/g;s/INDEX/${index}/g"${tmppage},说到底是sed命令的功劳。将weblist.txt里面的内容替换掉模板里的WEBURL和INDEX变量。
4、调用方式
sh./create.shwebcheck.templateweblist.txt
或者
sh./create.shweblist.txt
如果存在大量需要手工修改配置文件的情况下,或者批量生成一些类似的文件时可以考虑采用此种方式。