Kshitiz Gupta
Kshitiz Gupta

Reputation: 248

Using expect script to do an ssh from a remote machine

I am new to expect scripts and have a use case in which I need to do an ssh from a machine in which I have already done an ssh using expect script. This is my code snippet

#!/usr/bin/expect -f
set timeout 60
spawn ssh [email protected]

expect "Password: "
send "Password\r"

send "\r" # This is successful. I am able to login successfully to the first machine

set timeout 60
spawn ssh [email protected]  #This fails

This takes a some amount of time and fails saying ssh: connect to host machine2.domain.com port 22: Operation timed out. I understand that 22 is the default port on which ssh runs and I can manually override it by giving a -p option to ssh.

If I try to ssh independently without the expect script I get a prompt that asks me to enter (yes/no). From where is the correct port being picked up if I execute ssh directly without the expect script. If I do not need to enter the port number on shell why would it be needed to enter a port number if I am using an expect script.

Upvotes: 0

Views: 30393

Answers (1)

glenn jackman
glenn jackman

Reputation: 247112

That that point, you don't spawn a new ssh: spawn creates a new process on your local machine. You just send a command to the remote server

#!/usr/bin/expect -f
set timeout 60
spawn ssh [email protected]

expect "Password: "
send "Password\r"

send "\r" # This is successful. I am able to login successfully to the first machine

# at this point, carry on scripting the first ssh session:
send "ssh [email protected]\r"
expect ...

Upvotes: 5

Related Questions