cuitor

使用expect命令实现自动登录ssh

当我们在终端下需要连接ssh时,ssh命令会提示需要手动输入密码,会显得很繁琐。当然你可以选择将本机的ssh公钥放入服务器~/.ssh/authorized_keys来实现免密码登录,这里介绍的是使用expect命令实现密码的自动输入。

  1. 安装expect命令

    • OS X下安装

      brew install expect
      
    • Ubuntu下安装

      sudo apt-get install expect
      
  2. expect使用示例

    • ssh自动登录脚本

      #!/usr/bin/expect
      # ssh to server
      log_user 0
      set timeout 10
      spawn ssh root@yourServer.com
      expect {
          "(yes/no)?" {
              send "yes\
      "
              exp_continue
          }
          "assword:" {
              send "yourPassword\
      "
          }
      }
      interact
      
    • scpto自动拷贝脚本

      #!/usr/bin/expect
      # ssh to server
      set timeout 10
      set to [lindex $argv 0]
      set from [lindex $argv 1]
      if { $to == "" || $from == "" } {
          send_user "Usage: rcpto to from"
          exit 1
      }
      spawn scp $to root@yourServer.com:$from
      expect {
          "(yes/no)?" {
              send "yes\
      "
              exp_continue
          }
          "assword:" {
              send "yourPassword\
      "
          }
      }
      interact
      
    • scpfrom自动拷贝脚本

      #!/usr/bin/expect
      # ssh to server
      set timeout 10
      set from [lindex $argv 0]
      set to [lindex $argv 1]
      if {$from == ""} {
          send_user "Usage: rcpfrom from \[to\]"
          exit 1
      }
      if {$to == ""} {
          set to [exec basename $from]
      }
      spawn scp root@yourServer:$from $to
      expect {
          "(yes/no)?" {
              send "yes\
      "
              exp_continue
          }
          "assword:" {
              send "yourPassword\
      "
          }
      }
      interact
      
  3. expect脚本
    expect脚本是由tcl语言写成,详细语法可以参考expect帮助tcl tutorial

评论