想搞一個使用ssh登陸批量ip地址執行命令,自動輸入密碼的腳本,可是ssh不能使用標準輸入來實現自動輸入密碼,因而瞭解到了expect這個能夠交互的命令vim
Expect is a program that "talks" to other interactive programs according to a script. Following the script, Expect knows what can be expected from a program and what the correct response should be. An interpreted language provides branching and high-level control structures to direct the dialogue. In addition, the user can take control and interact directly when desired, afterward returning control to the script.
spawn:開啓一個進程,後面跟命令或者程序(須要作交互的,好比ssh) expect:匹配進程中的字符串 exp_continue:屢次匹配時用到 send:當匹配到字符串時發送指定的字符串信息 set:定義變量 puts:輸出變量 set timeout:設置超時時間 interact:容許交互 expect eof:
#!/usr/bin/expect #使用expect解釋器 spawn ssh root@192.168.56.101 #開啓一個進程ssh expect { "yes/no" { send "yes\r"; exp_continue } #當匹配到"yes/no時,就是須要你輸入yes or no時,發送yes字符串,\r帶表回車;exp_continue繼續匹配 "password:" { send "sanshen6677\r" } #當匹配到password,就是該輸入密碼,發送密碼,並\r回車。注意{以前要有空格。 } interact #容許交互,這樣你就會留在登陸以後的窗口,進行操做,沒有interact程序執行完成後就跳回當前用戶ip。
chmod +x sshlogin #添加權限直接執行 ./sshlogin 或者 expect sshlogin #使用expect解釋器執行
#!/usr/bin/expect set user [lindex $argv 0] #定義變量,接收從0開始,bash是從1開始 set ip [lindex $argv 1] set password [lindex $argv 2] spawn ssh $user@$ip expect { "yes/no" {send "yes\r"; exp_continue} "password" {send "$password\r"} } interact
./sshlogin root 192.168.56.101 password123
#!/usr/bin/expect set user [lindex $argv 0] set ip [lindex $argv 1] set password [lindex $argv 2] spawn ssh $user@$ip "df -Th" #執行一條命令 expect { "yes/no" {send "yes\r"; exp_continue} "password" {send "$password\r"} } expect eof
#!/usr/bin/bash 使用#bash解釋器 user=$1 ip=$2 password=$3 expect << EOF spawn ssh $user@$ip "df -Th" expect { "yes/no" {send "yes\r"; exp_continue} "password" {send "$password\r"} } expect eof EOF
bash sshlogin root 192.168.56.101 sanshen6677 #使用bash執行