3 min read · Aug 6, 2023
One way to connect an ec2 instance is executing this command:
ssh -i /path/to/your/key.pem [email protected]
Everytime when you login, you have to specify the path key.pem(private key) file. However, by performing few easy peasy steps, we can shorten the above command to:
ssh [email protected]
That means no need to keep pem file locally. One more advantage is, often times we use the same key-pair while creating new EC2 instance. And if we share the .pem file with a user, then they are open to connect to all the running EC2 instances(which is completely unnecessary). So rather than distributing private key file each users, admin/root user can perform the below stated method and the other user can login(restricted to required EC2 instance) without pem file .
1. Generate a SSH key pair on your local system
Open your terminal, and execute below command. Below command generates SSH key on Linux and MacOS.
ssh-keygen -t rsa
The -t
flag specifies the type of key to generate, and rsa
is the specific type of key being requested. RSA (Rivest-Shamir-Adleman) is a oldest and widely used public-key cryptosystem, known for its strong encryption and digital signature capabilities.
Instead of RSA, we can also generate ECDSA (Elliptic Curve Digital Signature Algorithm) key pair by specifying
-t ecdsa.
However, RSA keys are generally the most widely supported and commonly used for SSH authentication.
You will be prompted to enter filename(which is optional), it is asking where you want save the private key. If you keep it empty and press enter, then they keys will be saved at home_directory/.ssh/id_rsa
2. Copy the public key
Once the key pair is generated, you can view the public key using this command:
cat ~/.ssh/id_rsa.pub
Copy the content displayed on the terminal.
3. Login to EC2 instance
For one last time, just connect to your EC2 instance using the .pem file. And perform the following steps:
a) Make .ssh directory(if not present) in the current directory: mkdir ~/.ssh
b) Set the required folder permisson: chmod 700 ~/.ssh
c) Copy your public key from step-(2) inside an authorized_keys file.
echo "your public-key" >> ~/.ssh/authorized_keys
We don’t have to create authorized_keys files explicitly, the above command will create the required file and copy the content.
It is also possible that, .ssh folder already exists in your root directory. And authorized_key file already exists. Then just execute command given in (3.c)
d) Exit the EC2 instance and connect back using this command:
ssh [email protected]
In this brief blog post we saw how to log into an EC2 instance without being dependent on a private key file (.pem file).
PS: I will be publishing more short blogs similar to this. As, I use short blogs as a way to retain my knowledge, understanding, or something I recently learned or discovered, so that I may refer to it at any time in the future and anyone else can use it as well.