Quick Connect Remote (EC2 instance) and Host (User PC) through SSH command in Linux

How quickly can you connect your Remote Server from your host computer? In this blog, we are going to connect AWS EC2 instance from our personal laptop using the SSH and keygen command. This quick tip helps to instantly fire linux commands and start EC2 instance within seconds.

Settings in remote server

First ensure we are in home directory by using ‘$cd’ command

Then we need to setup .ssh folder in home directory

ubuntu@ipaddress $ cd .ssh/

Create a directory if this folder is not already created using ‘mkdir‘ command

$mkdir .ssh

Now see the contents of .ssh folder by using ls command

$ ls

You will then see the file with name ‘authorized_keys

If you didn’t find then create the file ‘authorized_keys’ using vi, vim, nano or any text editor.

The ssh key that you created during creating the instance will appear here. We will see the keys saved in this file. Later we will paste public key of our host computer (laptop) in this file.

Settings in Host PC

Ensure we are in home directory by using $ cd command

Then setup .ssh folder in home directory

Lists the contents in .ssh directory using ls command.

Now generate the public and private key of host computer by using ‘$ssh-keygen’ command. This will generate the id_rsa and id_rsa.pub files.

View using cat command and copy the content of public key file ‘id_rsa.pub’.

And paste the copied key to ‘authorized_keys’ file in remote(EC2 instance).

In Host PC, there must be ‘config’ file. If there is not then create the file using vi command.

In this config file, we will set up Host, HostName and User:

Host dev 
 	HostName <public ip address of EC2 instance>
        User <ubuntu> or <ec2-user> as per which ami we launched.

All settings are done, now to connect our remote server, we just need to type

$ssh dev’ in our host computer, and it will connect to our configured EC2 instance server within no time.

Note: If it shows permisson denied, we might have to configure IdentityFile below the User like this

Host dev 
 	HostName <public ip address of EC2 instance>
        User <ubuntu> or <ec2-user> as per which ami we launched.
        IdentityFile ~/.ssh/<generated private key>

We can add many EC2 instances in this config file, and copying the public key of our laptop to EC2 instance after which we can connect them quickly. This saves a lot of time, is one of the best method if we have development, production servers running, and need to switch multiple times.

Quick recap of above mentioned steps is shown below:

Remote
$ cd .ssh/
.ssh$ ls
authorized_keys
.ssh$ vi authorized_keys
Host 
$mkdir .ssh
$ ssh-keygen
$cd .ssh/
$ls
$vi id_rsa.pub
$vi config

Posted

in

, ,

by

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *