Following AWS best practices I’ve set up an infrastructure to which I ssh via a bastion box:

localhost → bastion → target server

To connect to the target server I have keyfiles on localhost and the bastion box, and then I use ssh to hop as follows:

localhost > ssh -i key.pem bastion
bastion > ssh -i key.pem target

It looks like this question is related. How do I execute a command on the target server from localhost directly?

2 Answers 2


You need to use ProxyCommand in your SSH config. So, in case you haven't set up your ~/.ssh/config, I'd refer to here

So You would want to do the following:

  1. Place the bastion as a Forward Agent in your SSH config.

  2. Use ProxyCommand to proxy your connection from the bastion to your target server.

Here is a quick example:

Host <bastion>
    ForwardAgent yes

Host <target_server>
        User <user>
        Hostname <Ip/Hostname>
        ProxyCommand ssh -q -W %h:%p <user>@<bastion> nc 2> /dev/null
        IdentityFile ~/.ssh/id_rsa

From the command line I use the following to execute remote commands, for instance to run top on the target system.

$ ssh -qt bastion "ssh -qt target \"top\"\"

This will even work with sudo or sudo su - user to run as a specific user.

$ ssh -qt bastion "ssh -qt target \"sudo su - user1 -c 'ls -l'\""

Here's what the ssh options in the examples do.

  • ssh -q = quiet, suppresses the banners from the server to miniminize distratctions.
  • ssh -t = terminal, forces allocation of a pseudo-terminal so that terminal oriented commands like top and sudo will accept the session as interactive.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .