Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using two interact in a Expect script

Tags:

linux

bash

expect

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.

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.

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:

Connection to my_linux.domain.com closed.
expect: spawn id exp4 not open
    while executing
"expect "root@my_linux:~#""
    (file "./aaa" line 11)
like image 452
MiddleCloud Avatar asked Feb 15 '14 20:02

MiddleCloud


1 Answers

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" 
like image 127
MiddleCloud Avatar answered Oct 03 '22 01:10

MiddleCloud