使用Expect SSH来服务器和执行命令 [英] Using expect to SSH to server and execute commands
问题描述
我想编写一个通用的Expect脚本,以通过SSH登录到系统并执行一些命令.我发现一个示例具有以下内容:
I want to write a generic expect script to login through SSH to a system and execute some commands. An example I found had the following:
#!/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个发送.想法?
...the script seems to login properly but it didn't execute the last 2 sends. Ideas?
启用exp_internal后,我注意到以下内容:
After enabling exp_internal, I noticed the following:
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
,因为我想覆盖提示.我认为我无法预测提示会是什么,因此,我不知道会出现什么模式.从上面看来,提示未更改.您如何解决这样的问题?
I'm trying to send PS1='>'\r
because I want to override the prompt. I don't think there's any way for me to predict what the prompt will be and therefore, I wouldn't know what pattern to expect. From the above, it looks like the prompt wasn't changed. How do you tackle a problem like this?
推荐答案
您的脚本似乎没有什么很明显错误(尽管使用其他提示可能使匹配容易一些) .这意味着它有些微妙.我建议添加以下内容:
There doesn't appear to be anything obviously wrong with your script (though using a different prompt might make matching a bit easier). Which means it is something subtle. I suggest adding this:
exp_debug 1
到脚本中的早期位置.它将使Expect引擎更多地打印 lot 关于它在做什么的信息,这(可能)可以帮助您了解问题所在,或者失败了,这会帮助此处的人帮助您……
to somewhere early in your script. It will make the Expect engine print a lot more about what it is doing, which will (probably) help you understand what is going wrong, or failing that help the people here help you…
这篇关于使用Expect SSH来服务器和执行命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!