分發系統—expect
expect是一種自動交互語言,能實現在shell腳本中爲scp和ssh等自動輸入密碼自動登錄。
登錄多臺系統執行指定命令;
創建文件最好以expect結尾;
安裝包
yum install -y expect
自動遠程登錄
1.expect
代碼:
#! /usr/bin/expect
set host "192.168.188.3"
set passwd "123456"
spawn ssh root@$host
expect {
"yes/no" { send "yes\r"; exp_continue}
"assword:" { send "$passwd\r" }
}
interact
說明:
- set host:設置變量host;
- send "yes":輸出yes;
- \r:回車
- “assword:”{ send “$passwd\r”} :獲取信息有assword:字樣,就輸入變量$passwd 回車;
- interact:不退出,停留登錄;
自動遠程登錄,執行命令並退出
2.expect
代碼:
#!/usr/bin/expect
set user "root"
set passwd "123456"
spawn ssh [email protected]
expect {
"yes/no" { send "yes\r"; exp_continue}
"password:" { send "$passwd\r" }
}
expect "]*"
send "touch /tmp/1.txt\r"
expect "]*"
send "echo 11111 > /tmp/1.txt\r"
expect "]*"
send "exit\r"
說明:
expect "]*":代表截取到]*字樣的命令時;其中*代表通配符;
傳遞參數
3.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"
expect "]*"
send "exit\r"
說明:
set user [lindex $argv 0]:定義變量user,指定它的參數爲第一個參數,由外界輸入提供;參數是有0開始;