在expect脚本中使用两个交互

Mid*_*oud 7 linux bash expect

我正在尝试编写一个通过SSH连接到Linux机器的脚本,并允许从那里交互式控制思科设备; 在我完成控制设备后,我也要退出外壳.

我有SSH密钥,不需要密码即可连接.go在下面的代码中是一个Bash脚本,通过SSH/telnet连接到目标设备.

到目前为止我所做的是:

#!/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
Run Code Online (Sandbox Code Playgroud)

我退出shell时得到的错误是:

Connection to my_linux.domain.com closed.
expect: spawn id exp4 not open
    while executing
"expect "root@my_linux:~#""
    (file "./aaa" line 11)
Run Code Online (Sandbox Code Playgroud)

Mid*_*oud 5

我已经解决了这个问题:

#!/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
Run Code Online (Sandbox Code Playgroud)

说明:我添加了几行:

# 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" 
Run Code Online (Sandbox Code Playgroud)

希望帮助任何人