使用expect工具實現zabbix agent自動化部署shell
Expect是在Tcl基礎上建立起來的,它還提供了一些Tcl所沒有的命令。
spawn命令激活一個Unix程序來進行交互式的運行。
send命令向進程發送字符串。
expect命令等待進程的某些字符串。
expect支持正規表達式並能同時等待多個字符串,並對每個字符串執行不一樣的操做bash
1. 安裝expect服務器
yum –y intall expectssh
2. 建立須要安裝zabbix agent的服務器列表文件 server.txt,格式爲ip地址 空格 密碼,能夠添加多臺。tcp
192.168.1.1 123456ide
192.168.1.2 123456工具
192.168.1.3 123456spa
….orm
3. 建立交互式自動安裝的expect腳本install.exp ,能夠選擇zabbix server上執行,IP地址爲192.168.1.254,密碼爲123456server
#!/usr/bin/expect -f
set ipaddress [lindex $argv 0]
set passwd [lindex $argv 1]
set timeout 30
spawn ssh root@$ipaddress
expect {
"yes/no" { send "yes\r";exp_continue }
"password:" { send "$passwd\r" }
}
expect "]#"
send "scp root@192.168.1.254:/usr/local/src/zabbix-1.8.2.tar.gz /usr/local/src\r"
expect {
"yes/no" { send "yes\r";exp_continue }
"password:" { send "123456\r" }
}
expect "]#"
send "useradd zabbix\r"
expect "]#"
send "cd /usr/local/src/\r"
expect "src]#"
send "tar zxf zabbix-1.8.2.tar.gz\r"
expect "src]#"
send "cd zabbix-1.8.2\r"
expect "zabbix-1.8.2]#"
send "./configure --prefix=/usr/local/zabbix --enable-agent >& /dev/null\r"
expect "zabbix-1.8.2]#"
send "make >& /dev/null\r"
expect "zabbix-1.8.2]#"
send "make install >& /dev/null\r"
expect "zabbix-1.8.2]#"
send "echo zabbix-agent 10055/tcp Zabbix Agent >> /etc/services\r"
send "echo zabbix-agent 10055/udp Zabbix Agent >> /etc/services\r"
send "mkdir /etc/zabbix\r"
send "cp misc/conf/zabbix_agent.conf /etc/zabbix/\r"
send "cp misc/conf/zabbix_agentd.conf /etc/zabbix/\r"
expect "zabbix-1.8.2]#"
send "sed -i \"82s#127.0.0.1#192.168.1.254#\" /etc/zabbix/zabbix_agentd.conf\r"
send "sed -i \"91s#Zabbix Server#\$HOSTNAME#\" /etc/zabbix/zabbix_agentd.conf\r"
send "sed -i \"201s/#//\" /etc/zabbix/zabbix_agentd.conf\r"
send "sed -i -e \"214s/#//\" -e \"214s/0/1/\" /etc/zabbix/zabbix_agentd.conf\r"
send "cp misc/init.d/fedora/core/zabbix_agentd /etc/init.d/\r"
expect "zabbix-1.8.2]#"
send "chmod a+x /etc/init.d/zabbix_agentd\r"
send "sed -i \"19s#/opt#/usr/local#\" /etc/init.d/zabbix_agentd\r"
send "sed -i \"25s#bin#sbin#\" /etc/init.d/zabbix_agentd\r"
send "chkconfig --add zabbix_agentd\r"
send "mkdir /etc/zabbix/zabbix_agentd\r"
expect "]#"
send "scp root@192.168.1.254:/etc/zabbix/zabbix_agentd/zabbix_agent.userparams.conf /etc/zabbix/zabbix_agentd\r"
expect {
"yes/no" { send "yes\r";exp_continue }
"password:" { send "123456\r" }
}
expect "]#"
send "/etc/init.d/zabbix_agentd start\r"
expect "]#"
send "exit\r"
4. 建立shell腳原本聯合執行以上2個文件,zabbix.sh
#!/bin/bash
for i in `awk '{print $1}' server.txt`
do
j=`awk -v I="$i" '{if(I==$1)print $2}' server.txt`
expect /root/install.exp $i $j
done
5. 執行./zabbix.sh 有交互信息,有錯誤可調整