When you create Amazon EC2 instance, you are given a RSA private key to access the instance. On Ubuntu Linux the key is for default user ubuntu which you can use to login.
It may be a good idea to create your own user and use ssh private and public key to automate all the ssh stuff. In fact you can use the same key at non EC2 servers also for making the key management simpler.
Here are the steps to automate login to Linux using ssh private/public keys. These instructions assume that you already have AWS EC3 Ububtu Linux instance where you can login using ubuntu user using the default private key generated during instance creation. The instructions should also work for other Linux flavors as well.
- Create a user on the box you want to setup ssh.
sudo adduser user1 --shell /bin/bash --home /home/user1
- Either you can use the key you got during AWS EC2 instance creation or you can create a new key using ssh-keygen. You can use some other key as well. To generate public key from private key use this command:
ssh-keygen -y -f private.pem > id_rsa.pub
- Create /home/user1/.ssh directory and append id_rsa.pub to /home/user1/.ssh/authorized_keys file.
sudo mkdir /home/user1/.ssh sudo chown user1 /home/user1/.ssh sudo chmod 755 /home/user1 sudo chmod 755 /home/user1/.ssh sudo cat /path/to/id_rsa.pub >> /home/user1/.ssh/authorized_keys sudo chown user1 /home/user1/.ssh/authorized_keys sudo chmod 644 /home/user1/.ssh/authorized_keys
Note that authorized_keys file should have 644 permission.
- Note that we don’t really need to copy private key here to ssh to this account. But to ssh from this account to other machines copy private.pem to .ssh dir.
sudo cp /some/path/private.pem /home/user1/.ssh/id_rsa sudo chown user1 /home/user1/.ssh/id_rsa sudo chmod 600 /home/user1/.ssh/id_rsa
Note that id_rsa file must have 600 permissions and no one other than owner should have any kind of access to it.
- Now you can ssh to this machine from your local machine (Mac or Linux) using this command:
ssh -i /path/to/private/key/private.pem firstname.lastname@example.org
When you run this first time, you will be asked to add the host to known_hosts. Just enter yes on prompt.
Some points to note
- The destination machine should have the public key in authorized_keys. That is enough for ssh.
- The source machine should have access to private key. If that key is present in .ssh directory as id_rsa then it is picked as default private key and -i option is not needed in ssh command.
- Private key should always have permission 600 and public key should have permission 644.