20.27 分發系統介紹 20.28 expect腳本遠程登陸 20.29 expect腳本遠程執行命令 20.30 expect腳本傳遞參數

20.27 分發系統介紹

分發系統:  可以把每段時間的最新代碼分別發佈到各服務器上去
上線: 就是把開發的代碼發佈到線上環境去

yum install -y expect

20.28 expect腳本遠程登陸

vim /usr/local/sbin/1.expect

//exp_continue 表示繼續   \r表示回車
interact 表示停留在遠程機器上,不退出, 若是去掉這句 則登陸後會立刻退出
expect eof 會停留在遠程機器上幾秒後退出


#自動遠程登陸
#! /usr/bin/expect
set host "192.168.192.135"
set passwd "123456"
spawn ssh root@$host
expect {
"yes/no" { send "yes\r"; exp_continue}    
"password:" { send "$passwd\r" }
}
interact

chmod a+x 1.expect  
./1.expect    測試是否自動登陸

若是你刪除了 vim /root/.ssh/known_hosts 中的內容, 第一次ssh登陸會有提示yes/no

20.29 expect腳本遠程執行命令

]*   表示 出來的提示符是 ] 後面是任意符號



#自動遠程登陸後,執行命令並退出
#! /usr/bin/expect
set user "root"
set passwd "123456"
spawn ssh $user@192.168.192.135
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"

20.30 expect腳本傳遞參數

傳遞參數


#!/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"
#send timeout -1    若是加上這句就永遠不超時, 也能夠設定幾秒超時, 如5秒 send timeout 5
expect "]*"
send "exit\r"

./3.expect root 192.168.192.135 ls
./3.expect root 192.168.192.135 "ls;w;pwd"    //執行多個命令
相關文章
相關標籤/搜索