expect免交互模式

目的:   避免交互模式,經常使用於機器登陸,磁盤分區須要在交互模式中進行的操做
工做原理:經過spwan啓動的程序都會被expect這個軟件識別或者監聽到,檢測屏幕出現的關鍵詞,發送一個指令,在shell內嵌中,能夠把指令導入到EOF中 << EOF開始 EOF結束shell

機器上必需要有這個expect工具,若是沒有須要安裝
yum install expectapache

1,expect有兩種寫法
 使用expect本身的解釋器,通常爲/usr/bin/expect
eg1:
#!/usr/bin/expect   此處的解釋器爲expect,由此程序解釋
spawn ssh 192.168.4.5
expect "password:" {send "redhat\r"} 檢測到password 這個字符就發送一個指令
expect "#" {send "mkdir /qq7\r"}
interact            容許交互式模式vim

___________________________________________________________________________________-bash

2,expect內嵌到shell中,使用shell解釋器
  兩種特殊狀況
  1)interact 優先級沒有shell高,打了也不可能down死
  2)expect 最後一條指令若是不是退出的話將不會執行,能夠寫個廢指令
eg2:ssh

#vim test.sh
#!/bin/bash           #注意這是shell解釋器不是expect
expect << EOF         #經過/bin/bash把expect啓動起來,把指令導入導入到expect中
spawn ssh 192.168.4.5  #經過spwan啓動的程序都會被expect這個軟件識別或者監聽到
expect {
 "yes/no"    { send "yes\r" ; exp_continue } # exp_contiune跳過屏幕繼續看下面的,有
 "password:" { send "123\r" }
}
EOF工具

#能夠設置expect超時時間  set timeout 60
set  用於設置變量
interact 容許交互式環境
導入: << EOF開始 EOF結束spa

___________________________________________________________________
eg3:pwa

#!/bin/bash
for i in $(cat list)
do
expect << EOF
swpan ssh $i
expect {
password {send "bmzy1mjr\r ;exp_contiune"}
yes/no   {send "yes\r"}
expect # {send "yum install httpd\r" ;exp_contiune}
expect # {send "exit\r"}
EOF
doneit

#目的:批量登陸到機器上去安裝apache,裝萬並推出,此類腳本易於擴展,須要執行的命令和操做,必定要在E0Ftest

相關文章
相關標籤/搜索