文本内容大致为:
exporter.log:
devops_monitor_prom_node-2 | CHANGED | rc=0 >>
root 26417 26416 0 02:27 pts/1 00:00:00 /bin/sh -c ps -ef |grep node_exporter
root 26419 26417 0 02:27 pts/1 00:00:00 grep node_exporter
gerrit1 | CHANGED | rc=0 >>
root 159753 159752 0 10:27 pts/4 00:00:00 /bin/sh -c ps -ef |grep node_exporter
root 159755 159753 0 10:27 pts/4 00:00:00 grep node_exporter
node_ex+ 201401 1 0 Jan08 ? 00:00:34 /usr/sbin/node_exporter --collector.textfile.directory /var/lib/node_exporter/te
xtfile_collector
gerrit_mirror | CHANGED | rc=0 >>
node_ex+ 120488 1 0 Jan08 ? 00:00:38 /usr/sbin/node_exporter --collector.textfile.directory /var/lib/node_exporter/te
xtfile_collector
要找到安装了node_exporter的hosts
把段落转成一行,按>>符号分隔
while read line ;do last2=echo ${line:0-2}
;if [ “$last2” == “>>” ];then echo ;echo -n $line;else echo -n $line;fi;done < ./exporter.log > 1exporter.log
过滤需要的结果
more 1exporter.log |grep “/usr/sbin/node_exporter”|awk ‘{print $1}’ > installed.log
得到到是主机名,把主机名转为ip
while read line ;do grep $line /etc/hosts|awk ‘{print $1}’;done < ./installed.log
得到ip列表。
将过程写成shell script
$ cat findIpsFromAnsibleLog.sh
#!/bin/sh
#$1:input a ansible log file
#$2:a key string to filter, only output hosts whose include key string.
#$3:if == "i" , filter will be inverse , only output hosts whose not include key string.
spliter=">>"
tmpfile="/tmp/ansible`date +%s`.1"
if [ "$1" == "" ];then #$1
echo input an ansible log file to handle.
else #$1
while read line ;do
last2=`echo ${line:0-2}`;
if [ "$last2" == "$spliter" ];then
echo ;
echo -n $line;
else
echo -n $line;
fi;
done < $1 > $tmpfile
if [ "$2" == "" ];then #$2
awk '{print $1}' $tmpfile
else #$2
if [ "$3" == "" ];then #$3
grep "$2" $tmpfile | awk '{print $1}'
else #$3
grep -v "$2" $tmpfile | awk '{print $1}'
fi #$3
fi #$2
fi #$1
rm $tmpfile