场景介绍:运行php代码时,首先须要搭建LAMP或LNMP环境,而后将代码上传到服务器上去,可是因为业务发展,代码更新频繁,若是机器台数比较多,手工上传代码就比较麻烦,而且不专业,这时咱们能够作一个代码分发系统,天天或者每隔一段时间的代码分别发布到这些机器上去php
主要工具expect:这是一种与shell很像的语言,能够用来传输文件、远程执行命令,不须要输入密码shell
准备工做:
一、准备一个模板机器放置准备上线的代码
二、待接收代码的机器的IP 登陆机器的帐号及密码
三、使用expect脚本,借助rsync将代码推送到接收机器上去bash
安装服务器
# yum install -y expect
#! /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
而后修改文件权限并执行脚本ssh
[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 ~]#
#!/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]#
#!/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"
而后咱们来执行这个脚本spa
这里输入代码
#!/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
#!/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
rsync.expect 内容code
#!/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内容ip
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