Muye
Muye

Reputation: 175

Automate SSH connection over proxy server

I am trying to write a very simple bash script, so I can first ssh to a proxy server, then from the proxy server, ssh to a destination server. This is how the network was set up to be accessed. I have:

#! /bin/bash
ssh  proxyservername
ssh  destservername

Which does not work. When I am connected to proxyserver, the second line of ssh is not executed, I still need to manually type in the command. Is there some commands I can add to the script, so I can be connected to destination server automatically? (I'm ok with being prompted for password.)

Upvotes: 0

Views: 468

Answers (2)

kirelagin
kirelagin

Reputation: 13626

I think the most common solution in similar situations is to use the -R flag of ssh (check man ssh). You might also want to read about -f and -o ExitOnForwardFailure=yes.

The pattern I use is something like this:

ssh -f -o ExitOnForwardFailure=yes -R localhost:2222:$TARGETNAME:22 $PROXYNAME sleep 1 &&
ssh -p 2222 localhost

(where 2222 is basically any port you can use on the local machine).

The -R flag tells ssh to connect to $PROXYNAME, set up a tunnel from there to port 22 of $TARGETNAME and attach its other end to port 2222 on you local machine. Other options tell ssh to go to background and close this connection when it is no longer used. Then you just start another ssh instance that connects to port 2222 on localhost.

Upvotes: 1

jrossi
jrossi

Reputation: 196

I think you need something along the lines of ssh proxyservername 'ssh destservername' assuming that proxyservername has ssh installed an access to destservername.

Upvotes: 0

Related Questions