Skip to content

Instantly share code, notes, and snippets.

@devmahmud
Last active May 24, 2024 13:40
Show Gist options
  • Save devmahmud/958b954cecb648c9349a55c009dbfbaa to your computer and use it in GitHub Desktop.
Save devmahmud/958b954cecb648c9349a55c009dbfbaa to your computer and use it in GitHub Desktop.
Generate pem file to login into remote server

We can use pem file to login into remote server from our local machines. Infact if you use AWS, the only way to SSH into the server is using pem file.

1. On your local Machine from where you require access, Home directory of the user is preferable

cd ~
ssh-keygen -t rsa -b 2048
Generating public/private rsa key pair.
Enter file in which to save the key (/home/user/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in example
Your public key has been saved in example.pub
The key fingerprint is:
SHA256:3IJlrYwRCxzGkaZwoXG0OSaJi8bHTLtzXLyC6GMZHLI mahmud@3xp1r3
The key's randomart image is:
+---[RSA 2048]----+
|..++=+.          |
|o=.+=. o .       |
|=o=+  o o .      |
|+==.. .O o       |
|=+.=  ooS .      |
|Eoo + . ..       |
| .o+ + .         |
|.+  o .          |
|...              |
+----[SHA256]-----+
In this case i have used example as a file name. so there will be two files example and example.pub
example : is your private key
example.pub : is your public key

2. Now it's time to create example.pem file from private key

rsa -in example -outform pem > example.pem

writing RSA key

If you don't have rsa utility you can create .pem file by using copy command

cp -p example example.pem

Now the pem file is created. Next step to copy public key(example.pub) to remote server

3. Copy the public key into your remote server, which needs to be accessed

ssh-copy-id -i example.pub root@1.2.3.4
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "example.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
root@1.2.3.4's password: 

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh 'root@1.2.3.4'"
and check to make sure that only the key(s) you wanted were added.

4. Change the permissions of your example.pem file

chmod 400 example.pem

5. Login to your remote server using example.pem file

ssh -i example.pem root@1.2.3.4

6. Disable SSH Access to remote server using password authentication

On the remote server with root access

nano /etc/ssh/sshd_config

Change parameter PasswordAuthentication yes to PasswordAuthentication no Restart SSH Daemon

systemctl restart sshd
or
service sshd restart
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment