expect能夠讓咱們實現自動登陸遠程機器,而且能夠實現自動遠程執行命令。固然如果使用不帶密碼的密鑰驗證一樣能夠實現自動登陸和自動遠程執行命令。但當不能使用密鑰驗證的時候,咱們就沒有辦法了。因此,這時候只要知道對方機器的帳號和密碼就能夠經過expect腳本實現登陸和遠程命令。ssh
yum install -y expect
ide
自動遠程登陸spa
#! /usr/bin/expect set host "192.168.85.132" #要遠程登陸的機器IP set passwd "123456" #遠程登陸的機器密碼 spawn ssh root@$host #登陸機器的語句 expect { "yes/no" { send "yes\r"; exp_continue} #初次登陸時須要輸入yes才能進入 "password:" { send "$passwd\r" } #當在遠程登陸時出現password:時自動輸入密碼 } interact #做用:表示須要停留在遠程的機器上,不須要退,若是不加就會退出來 #若是是 expect eof 就會在機器上停留一兩秒後退出來
自動遠程登陸後,執行命令並退出code
#!/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"
expect 「]*」 表示圖中括號裏的,表示當檢測到這個符號時就執行咱們要執行的命令blog
遠程登陸機器執行命令後退出it
遠程的機器執行命令後建立的文本和內容 class
傳遞參數登錄
#!/usr/bin/expect set user [lindex $argv 0] #把第一個參數的值賦給user 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" set timeout -1 #-1表示永遠不超時,1表示1秒,2表示2秒....,表示執行命令幾秒後中止 expect "]*" send "exit\r"