I have a script to connect to AWS via ssh. the content of the script is very simple:

#! /bin/bash
ssh -i private_key.pem ec2-user@ec2-11-11-111-11.us-west-2.compute.amazonaws.com

I run this script from the terminal:


And so I connect to this one AWS.

What I want to do is to connect from one AWS to second. Basically, after I run the script I can type

ssh second_aws

But I want to do it in one script such that I will run the script and my terminal will connect to second AWS, something like:

 #! /bin/bash
 ssh -i private_key.pem ec2-user@ec2-11-11-111-11.us-west-2.compute.amazonaws.com
 ssh second_aws

But if I will run this it moves to one AWS and doesn't connect to second AWS.

How can I use the script, run it from the terminal and my terminal will connect to the second computer?


Consider just telling the first host to execute the ssh command, instead of giving you a shell:

ssh -t -i private_key.pem ec2-user@ec2-11-11-111-11.us-west-2.compute.amazonaws.com ssh -t second_aws
  • Kooll!!! now it works!! thank you @Jeff Schaller – Eliya Aug 12 '19 at 15:32
  • ........Done ;) – Eliya Aug 12 '19 at 15:46

What you're doing does not open the second connexion from your AWS instance. It opens the connexion from the where the script is launched.

You should look for the ProxyJump option. It'll allow you to chain several SSH connexions.

Here's an extract from the man page :

         Specifies one or more jump proxies as either [user@]host[:port] or an ssh URI.  Multiple proxies may be separated by comma characters and will be visited sequentially.  Setting this option will cause ssh(1) to connect
         to the target host by first making a ssh(1) connection to the specified ProxyJump host and then establishing a TCP forwarding to the ultimate target from there.

         Note that this option will compete with the ProxyCommand option - whichever is specified first will prevent later instances of the other from taking effect.

         Note also that the configuration for the destination host (either supplied via the command-line or the configuration file) is not generally applied to jump hosts.  ~/.ssh/config should be used if specific configuration
         is required for jump hosts.
  • I want to use .pem file only for the first connection. And I don't see how to do it with ProxyJump. – Eliya Aug 12 '19 at 14:59

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.