場景介紹:運行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