想搞一個使用ssh登錄批量ip地址執行命令,自動輸入密碼的腳本,但是ssh不能使用標准輸入來實現自動輸入密碼,於是了解到了expect這個可以交互的命令
- 是什么
- 查看使用man查看expect,是這么說的,使用谷歌翻譯一下
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.
- 我是這么理解的,expect是一個程序,更准確來講是一個解釋型語言,用來做交互的
- 查看使用man查看expect,是這么說的,使用谷歌翻譯一下
- 命令
- 常用命令
spawn:開啟一個進程,后面跟命令或者程序(需要做交互的,比如ssh) expect:匹配進程中的字符串 exp_continue:多次匹配時用到 send:當匹配到字符串時發送指定的字符串信息 set:定義變量 puts:輸出變量 set timeout:設置超時時間 interact:允許交互 expect eof:
- 常用命令
- 簡單用法
- ssh登錄ip,自動輸入密碼,vim ~/sshlogin
#!/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解釋器執行
- 一般情況下用戶名,ip,密碼是需要作為參數傳進去的,因為和bash不一樣,所以使用$1接收是錯誤的。
#!/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
- ssh執行命令,需要在尾部加expect eof
#!/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
- 也可以使用bash,內部調用expect
#!/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執行
- ssh登錄ip,自動輸入密碼,vim ~/sshlogin