0

I need to write a script that connects to a remote server, then once connected, connects from there to another server, then changes directory. The following of course does not work (it connects to first server then the script is halted, and resumed once disconnected):

#!/bin/bash
echo begin:
ssh  serv_1
ssh  serv_2
cd dir1

exit 0

What do I need to do ? I read some posts with questions similar to mine, but I did not understand the answers.

  • If you want the second connection to happen from the first one, it needs to be run on that first server, not from your client. – Julie Pelletier Apr 30 '16 at 19:10
  • Ok, so there is no way to run all the commands above in one single script located on the client ? – Donald Apr 30 '16 at 19:14
  • Actually there is. A simple solution would be to use input redirection but a better approach would be to make a script on the first server. – Julie Pelletier Apr 30 '16 at 19:17
  • 1
    @Donald so you want to ssh serv1 and run some command then ssh serv2 and run some command in your script, right ? – Rahul Apr 30 '16 at 20:01
  • 1
    @Donald If you don't wanna do anything after ssh, then what is the point in sshing to serv1 and serv2 ? – Rahul Apr 30 '16 at 20:18
0

The short answer is,

ssh srv_1 'ssh srv_2 "command"'

where command is whatever command you want to run.

It also works without the single quotes, but I like them to aid in understanding.

ssh srv_1 ssh srv_2 "command"

Using the quotes gives us some structure to work within, but as you can see, they're not fundamentally necessary.

This also works,

ssh srv_1 ssh srv_2 command

We can't tell from the information you've given us if this will work, or if the command will do anything, but the above syntax is the approach I would take.

If you have to start using variables or command substitution then it'll get more complex, more quickly and you'll need to be careful with quoting and escaping.

Here's an example of it working.

Neptune is my host machine. Trinity is another server. Matrix is the final server.

tony@neptune:~$ ssh trinity 'ssh matrix "hostname"'
matrix

So the command returns the hostname matrix, because it has executed on the server matrix.

NB: Changing a directory in this way will have absolutely no effect, directory changes are relevant only to the shell in which they're executed.

Here's what I mean,

tony@Neptune:~$ ssh trinity 'ssh matrix "cd /tmp"'
tony@Neptune:~$ ssh trinity 'ssh matrix "pwd"'
/home/tony

The second command shows the previous cd command has had no lasting effect.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.