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执行
相关文章
相关标签/搜索