场景介绍:运行php代码时,首先需要搭建LAMP或LNMP环境,然后将代码上传到服务器上去,但是由于业务发展,代码更新频繁,如果机器台数比较多,手工上传代码就比较麻烦,并且不专业,这时我们可以做一个代码分发系统,每天或者每隔一段时间的代码分别发布到这些机器上去
主要工具expect:这是一种与shell很像的语言,可以用来传输文件、远程执行命令,不需要输入密码
准备工作:
1、准备一个模板机器放置准备上线的代码
2、待接收代码的机器的IP 登录机器的账号及密码
3、使用expect脚本,借助rsync将代码推送到接收机器上去
安装
# yum install -y expect
1.自动远程登录
#! /usr/bin/expect
#使用set定义变量
set host "192.168.75.134"
set passwd "123456"
spawn ssh root@$host
expect {
#如果是初次登录,当提示yes/no时,给对方发送yes,然后继续
"yes/no" { send "yes\r"; exp_continue}
# 提示密码时,就发送密码
"password:" { send "$passwd\r" }
}
#停留在远程机器上,不退出;另有一种用法expect eof表示登录后暂停一会儿后退出
interact
然后修改文件权限并执行脚本
[root@lijie-01 sbin]# chmod a+x 1.expect
[root@lijie-01 sbin]# ./1.expect
spawn ssh root@192.168.75.134
Last login: Mon May 7 23:30:55 2018 from 192.168.75.1
[root@lijie-02 ~]#
2、自动远程登录后,执行命令并退出
#!/usr/bin/expect
set user "root"
set passwd "123456"
spawn ssh $user@192.168.133.132
expect {
"yes/no" { send "yes\r"; exp_continue}
"password:" { send "$passwd\r" }
}
#这里的"]*"是用于检测是否登录成功,或者说检测是否处于待输入命令的状态。
expect "]*"
#创建一个文件
send "touch /tmp/12.txt\r"
expect "]*"
#给这个文件写入值
send "echo 1212 > /tmp/12.txt\r"
expect "]*"
#退出登录
send "exit\r"
然后我们来执行这个脚本
[root@lijie-01 sbin]# chmod a+x 2.expect //执行前需要先加入执行权限
[root@lijie-01 sbin]# ./2.expect
spawn ssh root@192.168.75.134
touch /tmp/12.txt
echo 1212>/tmp/12.txt
[root@lijie-01 sbin]#
3、传递参数
#!/usr/bin/expect
#把第一个参数的值赋给user
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"
然后我们来执行这个脚本
这里输入代码
4、自动同步文件
#!/usr/bin/expect
set passwd "123456"
spawn rsync -av root@192.168.133.132:/tmp/12.txt /tmp/
expect {
"yes/no" { send "yes\r"}
"password:" { send "$passwd\r" }
}
expect eof
5、指定host和要同步的文件
#!/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
6、文件分发系统的实现
rsync.expect 内容
#!/usr/bin/expect
set passwd "123456"
set host [lindex $argv 0]
set file [lindex $argv 1]
spawn rsync -av --files-from=$file / root@$host:/
expect {
"yes/no" { send "yes\r"}
"password:" { send "$passwd\r" }
}
expect eof
ip.list内容
192.168.133.132
192.168.133.133
......
rsync.sh 内容
#!/bin/bash
for ip in `cat ip.list`
do
echo $ip
./rsync.expect $ip list.txt
done
exe.expect 内容
#!/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"
exe.sh 内容
#!/bin/bash
for ip in `cat ip.list`
do
echo $ip
./exe.expect $ip "w;free -m;ls /tmp"
done