【问题标题】:Using expect to SSH to server and execute commands使用期望 SSH 到服务器并执行命令
【发布时间】:2012-10-23 19:19:53
【问题描述】:

我想编写一个通用的期望脚本来通过 SSH 登录到系统并执行一些命令。我发现的一个例子如下:

#!/usr/bin/expect

set fid [open ./.secret]
set password [read $fid]
close $fid
spawn /usr/bin/ssh root@[lindex $argv 0]
expect {
  -re ".*Are.*.*yes.*no.*" {
    send "yes\n"
    exp_continue
    #look for the password prompt
  }

  "*?assword:*" {
    send $password
    send "\n"
  }
}

send -- "PS1='>'\r"
expect -re ">$" { send "hostname\r" }
expect -re ">$" { send "pwd\r" }

...脚本似乎可以正确登录,但没有执行最后 2 次发送。想法?

编辑: 启用 exp_internal 后,我注意到以下内容:

expect: does "" (spawn_id exp4) match glob pattern "*"? yes
expect: set expect_out(0,string) ""
expect: set expect_out(spawn_id) "exp4"
expect: set expect_out(buffer) ""
send: sending "PS1='>'\r" to { exp4 }
Gate keeper glob pattern for '>$' is '>'. Activating booster.

expect: does "" (spawn_id exp4) match regular expression ">$"? Gate ">"? gate=no


expect: does "\r\n" (spawn_id exp4) match regular expression ">$"? Gate ">"? gate=no
Last login: Tue Nov  6 14:13:31 2012 from 1.x.x.x

expect: does "\r\nLast login: Tue Nov  6 14:13:31 2012 from 1.x.x.x\r\r\n" (spawn_id exp4) match regular expression ">$"? Gate ">"? gate=no

我正在尝试发送PS1='>'\r,因为我想覆盖提示。我认为我无法预测提示将是什么,因此,我不知道会出现什么模式。从上面看,提示似乎没有改变。你如何解决这样的问题?

【问题讨论】:

  • 可能是您发送提示配置太快了。听听 Donal 的建议,或使用exp_internal 1(不确定这两个命令之间的确切区别)。
  • 来自“NEWS”文件:-- The old "debug" command (which describes what Expect is doing internally) was renamed "exp_internal". "debug" (and "exp_debug") now invoke the interactive debugger. 我试过了,它确实是交互式的,在每一步之后都会中断并允许您发出期望命令。我发现它在调试一些正则表达式时很有用。方便,但总的来说,我发现 exp_internal 更方便。

标签: tcl expect


【解决方案1】:

您的脚本似乎显然没有任何问题(尽管使用不同的提示可能会使匹配更容易一些)。这意味着它是微妙的。我建议添加这个:

exp_debug 1

到脚本早期的某个地方。它会让 Expect 引擎打印出更多关于它正在做什么的很多,这将(可能)帮助你了解哪里出了问题,或者帮助这里的人帮助你……

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-07
    • 2013-11-22
    相关资源
    最近更新 更多