Shitanshu Lall
Shitanshu Lall

Reputation: 1

How to execute multiple commands on remote host connected using dual SSH connection?

I have two remote server and i am trying to execute more than one command on a remote host to which i am connected by using ssh command. My command syntax is like:

ssh -t -i key-1 user1@remote-1 "ssh -t -i key-2 user2@remote-2 "cmd-1;cmd-2;...cmd-n;"";

I have tried using semi-colon (;) and && symbols between two commands and observed that first command executes on remote-2 and second command executes on remote-1.

My requirement is that I want to execute all commands except the last one on remote-2. And, the last command on remote-1.

Note: I know how to execute multiple commands by connecting to single remote host. So, I will appreciate if answer is given only after understanding the problem statement.

Upvotes: 0

Views: 1987

Answers (2)

dash-o
dash-o

Reputation: 14422

Instead of single-line, consider taking advantage of here-documents to simplify the sequence. It has the advantage of making it easier to enter long commands.

ssh -t -i key-1 user1@remote-1 <<__END__
    ssh -t -i key-2 user2@remote-2 "cmd-1;cmd-2;..."
    cmd-n
__END__

I'm not able to test locally, but should be possible to nest further

ssh -t -i key-1 user1@remote-1 <<__END__
    ssh -t -i key-2 user2@remote-2 <<__SUB__
        # Execute on remote2
        cmd-1
        cmd-2
        ...
__SUB__
    # Execute on remote1
    cmd-n
__END__

Upvotes: 0

th3ant
th3ant

Reputation: 338

Assuming that you cannot create config files to simplify your command on the two hosts, and that you do not want to split this into two separate commands, it should be as simple as moving the last command out of the inner SSH command:

ssh -t -i key-1 user1@remote-1 "ssh -t -i key-2 user2@remote-2 \"cmd-1;cmd-2;...cmd-n-1\"; cmd-n"

# or

ssh -t -i key-1 user1@remote-1 'ssh -t -i key-2 user2@remote-2 "cmd-1;cmd-2;...cmd-n-1"; cmd-n'

You should also escape your double nested quotes, or simply change your outer/inner quotes to single quotes providing you are not expanding within this command.


Also as an aside, you can simplify your SSH command greatly by using a .ssh_config file, specifically with the ProxyJump parameter (man page).

Upvotes: 0

Related Questions