搭建splunk,需要在N台服务器上安装splunkforward,操作重复。求助运维无果,求助同事给的解决方案是使用TCL脚本。

所做的事情,往N台服务器上上传splunkforward压缩包,解压,修改配置文件,启动。其中远程机器ip、用户名、密码、需要修改的配置文件的内容都放在my.conf文件中,脚本遍历该文件进行操作。

运行本脚本的机器,需要安装tcl,如果联网直接 yum install expect 即可。

start.sh

#!/bin/bash
my_home=/home/wangc/script
splunk_file_name=splunkforwarder-7.0.tar.gz
cat ${my_home}/my.conf |grep -v '#' | grep -v '^$' |while read line
do
    host=$(echo $line |awk '{printf $1}')
    username=$(echo $line |awk '{printf $2}')
    passwd=$(echo $line |awk '{printf $3}')
    passwd_su=$(echo $line |awk '{printf $4}')
    log_path=$(echo $line |awk '{printf $5}')
    log_idx=$(echo $line |awk '{printf $6}')
    log_type=$(echo $line |awk '{printf $7}')
    ${my_home}/connecthost.tcl ${username} ${passwd} ${host} ${passwd_su} ${log_path} ${log_idx} ${log_type} ${splunk_file_name}
done

connecthost.tcl

#!/usr/bin/expect
#将文件传输到远程机器,并且根据配置文件修改文件中的信息

set timeout 20
set username [lindex $argv 0]
set passwd [lindex $argv 1]
set host [lindex $argv 2]
set passwd_su [lindex $argv 3]
set logpath [lindex $argv 4]
set indexname [lindex $argv 5]
set typename [lindex $argv 6]
set splunk_file_name [lindex $argv 7]
if { $argc != 8 } {
puts "Passing parameters abnormal!"
exit
}
spawn scp -o StrictHostKeyChecking=no ./$splunk_file_name $username@$host:/tmp
expect "password:"
send "$passwd\r"
expect eof
spawn ssh -o StrictHostKeyChecking=no $username@$host
expect "
password:"
send "$passwd\r"
expect "]"
send "su - root\r"
expect "Password:"
send "$passwd_su\r"
expect -re "]|$|#"
send "mv -f /tmp/$splunk_file_name /usr/local\r"
expect -re "]|$|#"
send "cd /usr/local\r"
expect -re "]|$|#"
send "tar zxf $splunk_file_name\r"
expect -re "]|$|#"
send "rm -rf $splunk_file_name\r"
expect -re "]|$|#"
send "cd /usr/local/splunkforwarder/etc/system/local\r"
expect -re "]|$|#"
send "sed 's/xx_ip_xx/'${host}'/g' inputs.conf > inputs.conf.tmp1\r"
expect -re "]|$|#"
send "sed 's/xx_logpath_xx/'${logpath}'/g' inputs.conf.tmp1 > inputs.conf.tmp2\r"
expect -re "]|$|#"
send "sed 's/xx_indexname_xx/'${indexname}'/g' inputs.conf.tmp2 > inputs.conf.tmp3\r"
expect -re "]|$|#"
send "sed 's/xx_typename_xx/'${typename}'/g' inputs.conf.tmp3 > inputs.conf.tmp4\r"
expect -re "]|$|#"
send "mv -f inputs.conf.tmp4 inputs.conf\r"
expect -re "]|$|#"
send "rm -f inputs.conf.tmp1 inputs.conf.tmp2 inputs.conf.tmp3\r"
expect -re "]|$|#"
send "/usr/local/splunkforwarder/bin/splunk start --accept-license\r"
expect -re "]|$|#"
send "exit\r"
expect -re "]|$|#"
send "exit\r"
expect eof

my.conf(配置文件,依次是:远程ip、用户名、密码、root密码,后三项是需要修改的文件内容)

10.7.13.141 zangs 123456 000000 \/home\/zangs\/a.log idx_a dty_a
10.7.13.142 wangc 000000 000000 \/home\/wangc\/b.log idx_b dty_b