首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何让expect脚本提示输入密码?

如何让expect脚本提示输入密码?
EN

Stack Overflow用户
提问于 2009-03-25 14:47:35
回答 2查看 44.7K关注 0票数 25

我有一个expect脚本,它通过ssh连接到几个路由器。所有这些路由器都有相同的密码(我知道这是错误的),脚本需要知道该密码才能连接到路由器。目前,密码作为参数在命令行传递给我的脚本,但这意味着在我的.bash_history文件和正在运行的进程中都有该密码的踪迹。因此,我希望提示用户输入密码,如果可能的话,可以静默输入。

您是否知道是否可以使用expect提示用户输入密码?

谢谢。

编辑:如果我连接到服务器而不是路由器,我可能会使用ssh密钥而不是密码。但我使用的路由器只支持密码。

EN

回答 2

Stack Overflow用户

发布于 2011-01-25 03:19:12

好的,合并上面的两个答案(或者下面或者他们现在所在的任何地方!):

代码语言:javascript
复制
#!/usr/bin/expect
log_user 0
set timeout 10
set userid  "XXXXX"
set pass    "XXXXXX"

### Get two arguments - (1) Host (2) Command to be executed
set host    [lindex $argv 0] 
set command [lindex $argv 1]

# grab the password
stty -echo
send_user -- "Password for $userid@$host: "
expect_user -re "(.*)\n"
send_user "\n"
stty echo
set pass $expect_out(1,string)

spawn /usr/bin/ssh -l $userid $host
match_max [expr 32 * 1024]

expect {
    -re "RSA key fingerprint" {send "yes\r"}
    timeout {puts "Host is known"}
}

expect {
     -re "username: " {send "$userid\r"} 
     -re "(P|p)assword: " {send "$pass\r"}
     -re "Warning:" {send "$pass\r"}
     -re "Connection refused" {puts "Host error -> $expect_out(buffer)";exit}
     -re "Connection closed"  {puts "Host error -> $expect_out(buffer)";exit}
     -re "no address.*" {puts "Host error -> $expect_out(buffer)";exit}

     timeout {puts "Timeout error. Is host down or unreachable?? ssh_expect";exit}
}

expect {
   -re "\[#>]$" {send "term len 0\r"}
   timeout {puts "Error reading prompt -> $expect_out(buffer)";exit}
}


expect {
   -re "\[#>]$" {send "$command\r"}

   timeout {puts "Error reading prompt -> $expect_out(buffer)";exit}
}

expect -re "\[#>]$"
set output $expect_out(buffer)
send "exit\r"
puts "$output\r\n"

请注意,为了与另一个答案一致,我将$password变量更改为$pass。

票数 8
EN

Stack Overflow用户

发布于 2011-02-12 02:45:44

或者,您可以使用SSH_ASKPASS环境变量让ssh通过X11收集密码。

从手册页:

代码语言:javascript
复制
> SSH_ASKPASS
>     If ssh needs a passphrase, it will read the passphrase from the
>     current terminal if it was run from a terminal.  If ssh does not
>     have a terminal associated with it but DISPLAY and SSH_ASKPASS
>     are set, it will execute the program specified by SSH_ASKPASS
>     and open an X11 window to read the passphrase.  This is particularly
>     useful when calling ssh from a .xsession or related script.
>     (Note that on some machines it may be necessary to redirect the
>     input from /dev/null to make this work.)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/681928

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档