Question

I want to write a script that automatically connects me via SSH to a given IP, and after that opens a telnet session from where it just connected.

My expect code till now:

# $1 = ssh root@111.111.111.111
# $2 = password
# $3 = telnet 123.123.123.123 10023

(expect -c "
            set timeout 20
            spawn $1
            expect {
                    \"Password:\" { send \"$2\r\" }
                    timeout { send_error \"\nTimeout!\n\"; exit 1; } 
            }
            spawn $3
            interact
            "  )

My problem is that I cannot spawn the telnet in the ssh session, the script is just "telnetting" from my home directory. Maybe there is a way with session ids, but I could not find helpful information.

Would be nice if someone of you could suggest some solution or workaround, thanks in advance and please excuse my bad English skills :)

Edit:

What helped with my problem, was:

(expect -c "
            set timeout 20
            spawn ssh root@server telnet server2
            expect {
                    \"Password:\" { send \"$2\r\" }
                    timeout { send_error \"\nTimeout!\n\"; exit 1; } 
            }
            interact
            "  )
Was it helpful?

Solution

I'd have a bit of a different approach for you, easier maybe.
As I understand it:
You want to SSH into a server of yours and from there telnet to another place

Did you consider using key based authentication with SSH ? For this approach you would add your identity key to .ssh/authorized_keys on the remote server.
Here is an example which uses expect from command line, connects to a SSH server using a key file and from there connects to a mailserver and sends "HELO test"
Tested it on my servers, works

expect -c 'expect "\n" {eval spawn ssh -i identity_file my.sshserver.com telnet mail.anotherserver.com 25; expect "SMTP" {send "HELO test\r\n"};interact}'

you can also add a timeout option to ssh (-oConnectTimeout)

It will connect to the server and call the telnet command, so you would have an open SSH session which has telnet already connected.
The script waits for an initial ENTER from you to start.

OTHER TIPS

As you also asked for a Workaround, here is one: You can use ssh port forwarding

ssh -f -N -n root@111.111.111.111 -L 10024:123.123.123.123:10023

[wait for connecting]

telnet localhost 10024

Here, ssh will open a connection and go into background. the local ssh client will listen on port 10024 and redirect all traffic to 123.123.123.123 port 10023. As long as this ssh instance is running, you can open and use telnet sessions (From the initial location).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top