当业务逐渐越来越大,服务端上传网站或者APP代码时,一旦服务器数量较多时就变的极为不方便,而公司本身并没有上线自动化运维工具时,可以使用shell脚本来编写一个分发系统,其中核心使用expect脚本语言,他可以实现远程执行命令,远程传输数据等操作。
二、expect脚本远程登录
#! /usr/bin/expect
set host "192.168.157.130"
set passwd "123456"
spawn ssh root@$host
expect {
"yes/no" { send "yes\r"; exp_continue}
"assword:" { send "$passwd\r" }
}
interact
#!/usr/bin/expect
set user "root"
set passwd "123456"
spawn ssh [email protected]
expect {
"yes/no" { send "yes\r"; exp_continue}
"password:" { send "$passwd\r" }
}
expect "]*"
send "touch /tmp/expect.txt\r"
expect "]*"
send "echo 1212 > /tmp/expect.txt\r"
expect "]*"
send "exit\r"
#!/usr/bin/expect
set user [lindex $argv 0]
set host [lindex $argv 1]
set passwd "123456"
set cm [lindex $argv 2]
spawn ssh $user@$host
expect {
"yes/no" { send "yes\r"}
"password:" { send "$passwd\r" }
}
expect "]*"
send "$cm\r"
expect "]*"
send "exit\r"
#!/usr/bin/expect
set user [lindex $argv 0]
set host [lindex $argv 1]
set passwd "123456"
set cmd [lindex $argv 2]
spawn ssh $user@$host
expect {
"yes/no" {send "yes\r"}
"password:" {send "$passwd\r"}
}
expect "]*"
send "$cmd\r"
set timeout -1
expect "]*"
send "exit\r"
五、expect脚本同步文件
#!/usr/bin/expect
set passwd "123456"
spawn rsync -av [email protected]:/tmp/expect.txt /tmp/
expect {
"yes/no" { send "yes\r"}
"password:" { send "$passwd\r" }
}
expect eof
#!/usr/bin/expect
set passwd "123456"
set host [lindex $argv 0]
set file [lindex $argv 1]
spawn rsync -av $file root@$host:$file
expect {
"yes/no" { send "yes\r"}
"password:" { send "$passwd\r" }
}
expect eof
#!/usr/bin/expect
set passwd "123456"
set host [lindex $argv 0]
set file [lindex $argv 1]
#无法保证远程同步的机器有相同目录时,可以加上-R选项,级联的创建目录。
spawn rsync -avR --files-from=$file / root@$host:/
expect {
"yes/no" { send "yes\r"}
"password:" { send "$passwd\r" }
}
expect eof
#!/bin/bash
for ip in `cat ip.list`
do
echo $ip
./rsync.exp $ip file.list
done
当同步完代码后有可能需要批量地重启服务,因此还需要批量远程执行命令,类似于自动化。
#!/usr/bin/expect
set host [lindex $argv 0]
set passwd "123456"
set cm [lindex $argv 1]
spawn ssh root@$host
expect {
"yes/no" { send "yes\r"}
"password:" { send "$passwd\r" }
}
expect "]*"
send "$cm\r"
expect "]*"
send "exit\r"
#!/bin/bash
for ip in `cat ip.list`
do
echo $ip
./exe.exp $ip "w;free -m;ls /tmp"
done