linux ssh自动输入密码,expect使用

想搞一个使用ssh登录批量ip地址执行命令,自动输入密码的脚本,但是ssh不能使用标准输入来实现自动输入密码,于是了解到了expect这个可以交互的命令

  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执行
posted @ 2019-10-15 16:28  故道丶白云  阅读(9036)  评论(0编辑  收藏  举报