用expect进行ssh登录和执行命令

expect是一个用来模拟用户命令行交互过程的程序。可以用来进行自动化操作和批量操作。

下面是一个典型的自动登录并执行命令的expect脚本。

脚本总共用到两个expect命令,第一个expect主要用于登录。第二个exepct命令用于执行批处理命令。

由于多数Shell操作是一个典型的REPL(Read–Eval–Print Loop)操作。下面的例子脚本巧妙地借助exp_continue命令模拟了一个REPL操作,仅通过一个expect语句实现多条命令的执行。

#!/usr/bin/env expect
########################################################
# by noyesno, at 2017/08/19                            #
########################################################

lassign $argv remote_user remote_host
set prompt "shell >"

spawn "ssh -l $remote_user $remote_host"

expect {
  "password:" {
    send_user "ssh password: "
    expect_user -re "(.*)\n"
    set ssh_password $expect_out(1,string)
    send "$ssh_password\r"
    exp_continue
  }
  -ex $prompt {
    send_user "OK login\n"
    send "echo hello\r"
  }
  timeout {
    send_error "remote response timeout"
  }
  eof {
    send_error "remote closed"
  }
}

set commands {
  "pwd"
  "env"
  "ls -lrt"
  "exit"
}

expect {
  -ex $prompt {
    set commands [lassign $commands command]
    send "$command\r"
    exp_continue
  }
}

exit