Any way I can SSH into multiple servers (from local to servA and then from servA to servB) using a local script? [closed]

StackOverflow https://stackoverflow.com/questions/23368568

  •  12-07-2023
  •  | 
  •  

Question

I have two difficulties.

Q1.

I log into 'servA' using ssh userA@servA from local terminal, then from 'servA' I log into 'servB' using ssh userB@servB and cd into my working directory on 'servB' and execute 'programA' (servB cannot be connected from local). Every time I need to do this process manually and input my password twice (once for servA, once for servB).

Can I make the procedure above simply by running a bash script at local terminal?

Q2.

I want to copy data from local to servB and vice versa. Currently, I copy data from local to servA using scp and then from servA to servB. Is there a solution to transfer data directly between local and servB?

Was it helpful?

Solution

Easiest is to use the ssh connection to servA to setup a tunnel:

ssh -L50022:servB:22 user@servA

You can then connect to the ssh daemon on servB by accessing localhost:50022, the conversation is forwarded or "tunneled" to servB:

ssh -p 50022 user@localhost

or

scp -P 50022 /some/local/file user@localhost:/home/user/

You can automate that by putting it in a script. But then you have to take care that the first call (to setup the tunnel) does not block the script:

ssh -T -L50022:servB:22 user@servA &
scp -P 50022 /some/local/file user@localhost:/home/user/

OTHER TIPS

For the ssh hop, I used something very similar to this:

ssh -A -t hopserver ssh -A finalserver

from here. I created a bash alias hop with something like

alias hop="ssh -A -t hopserver ssh -A"

so I could just type

hop finalserver

you can set access details up for each machine in your .ssh/config, and you'll want to put your ssh public key in .ssh/authorized_keys on each of the machines involved if you want to skip password authentication.

Hope that helps.

In ~/.ssh/config, specify a ProxyCommand which uses servA to connect to servB.

Host servB
    ProxyCommand ssh -W %h:%p userA@servA

Then ssh servB will log you into servB via servA. The %h and %p take the host and port number used in the original command, although this situation doesn't require anything so general.

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