Skip to content

Instantly share code, notes, and snippets.

@mhimanshu0101
Created January 29, 2022 12:59
Show Gist options
  • Save mhimanshu0101/0bc16289dc637a5d8f94dc0f00191d08 to your computer and use it in GitHub Desktop.
Save mhimanshu0101/0bc16289dc637a5d8f94dc0f00191d08 to your computer and use it in GitHub Desktop.
Access AWS EC2 instance using SSH with .pem file

Access AWS EC2 SSH with your .pem file

For linux distribution

  1. Generate keygen for your local system
    ssh-keygen -t rsa -C '<email>'

  2. change permission of ssh key file to read only
    chmod 400 ~/.ssh/id_rsa

For WSL distribution

  1. Copy .pem file too .ssh directory
    cp file.pem ~/.ssh/
  2. change permission of .pem file to read only chmod 600 ~/.ssh/file.pem

Access now as:
ssh -i your_pem_file.pem ubuntu@ec2-________.compute-1.amazonaws.com

Access AWS EC2 SSH with username and password

To setup this flow, first Login to your EC2 instance using your .pem file and follow steps below

  1. Add new user that will access the instance using password. sudo useradd -s /bin/bash -m -d /home/USERNAME -g root USERNAME where:
  • s /bin/bash : use /bin/bash as the standard shell
  • m -d /home/USERNAME : create a home directory at /home/USERNAME
  • g root : add to group root
  • USERNAME : the username of the new user
  1. Create a strong password for the new user: $ sudo passwd USERNAME
  Enter new UNIX password:
  Retype new UNIX password:
  1. Add user to sudoers file by using sudo visudo and add the following line: USERNAME ALL=(ALL:ALL) ALL
  2. Enable password authentication by editing /etc/ssh/sshd_config: change PasswordAuthentication no to PasswordAuthentication **yes**
  3. Restart ssh service:
    sudo /etc/init.d/ssh restart
  4. Logout of your instance (exit) and try your new login without the .pem file:
$ ssh USERNAME@ec2-________.compute-1.amazonaws.com
USERNAME@ec2-________.compute-1.amazonaws.com's password:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment