linux ssh自動輸入密碼,expect使用

想搞一個使用ssh登陸批量ip地址執行命令,自動輸入密碼的腳本,可是ssh不能使用標準輸入來實現自動輸入密碼,因而瞭解到了expect這個能夠交互的命令vim

  1. 是什麼
    • 查看使用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是一個程序,更準確來說是一個解釋型語言,用來作交互的
  2. 命令
    • 經常使用命令
      spawn:開啓一個進程,後面跟命令或者程序(須要作交互的,好比ssh)
      expect:匹配進程中的字符串
      exp_continue:屢次匹配時用到
      send:當匹配到字符串時發送指定的字符串信息
      set:定義變量
      puts:輸出變量
      set timeout:設置超時時間
      interact:容許交互
      expect eof:
  3. 簡單用法
    • 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執行
相關文章
相關標籤/搜索