bash 在期望脚本中使用两个交互
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21803337/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using two interact in a expect script
提问by MiddleCloud
I'm trying to write a script that connects to a Linux box via SSH and allows interactive control of Cisco equipment from there; after I finish controlling the equipment, I want to exit the shell, too.
我正在尝试编写一个脚本,该脚本通过 SSH 连接到 Linux 机器,并允许从那里对 Cisco 设备进行交互式控制;控制完设备后,我也想退出shell。
I have SSH keys and do not need a password to connect. go
in the code below is a Bash script that connects to the target equipment via SSH/telnet.
我有 SSH 密钥,不需要密码即可连接。go
下面的代码中是一个 Bash 脚本,它通过 SSH/telnet 连接到目标设备。
What I have done so far is:
到目前为止我所做的是:
#!/usr/bin/expect
set arg1 [lindex $argv 0]
spawn ssh -p 24 my_username@my_linux.domain.com
expect "#"
send "go $arg1 \n"
expect "sername:"
send "my_username\n"
expect "assword:"
send "my_password\n"
interact
expect "root@my_linux:~#"
send "logout\n"
expect "my_username@my_linux:~ $"
send "logout\n"
interact
The error I get when I exit the shell is:
退出shell时出现的错误是:
Connection to my_linux.domain.com closed.
expect: spawn id exp4 not open
while executing
"expect "root@my_linux:~#""
(file "./aaa" line 11)
采纳答案by MiddleCloud
I have resolved the problem:
我已经解决了这个问题:
#!/usr/bin/expect
set timeout -1
set arg1 [lindex $argv 0]
spawn ssh -p 24 my_username@my_linux.domain.com
expect "#"
send "go $arg1 \n"
expect "sername:"
send "my_username\n"
expect "assword:"
send "my_password\n"
expect "#"
interact timeout 5 return
send "\n"
expect "root@my_linux:~#"
send "exit\n exit\n"
interact
Explanation: I added a few lines:
说明:我添加了几行:
# This prevents commands from timing out (default timeout is 10 seconds).
set timeout -1
# When I type something, the timeout is ignored, but when I'm not typing,
# it waits 5 seconds and then continues.
interact timeout 5 return
send "\n"
expect "root@my_linux:~#"
send "exit\n exit\n"
Hope helps anyone
希望可以帮助任何人