Creating New User and Adding SSH Keys to instance

Create Key Pair

The first step is to create a key pair on the client machine (usually your computer):

$ ssh-keygen

After entering the command, you should see the following output:

Generating public/private rsa key pair.
Enter file in which to save the key (/your_home/.ssh/id_rsa):

Press ENTER to save the key pair into the .ssh/ subdirectory in your home directory, or specify an alternate path.

You should then see the following output:

Your identification has been saved in /your_home/.ssh/id_rsa.
Your public key has been saved in /your_home/.ssh/
The key fingerprint is:
a9:49:2e:2a:5e:33:3e:a9:de:4e:77:11:58:b6:90:26 username@remote_host
The key's randomart image is:
+--[ RSA 2048]----+
|     ..o         |
|   E o= .        |
|    o. o         |
|        ..       |
|      ..S        |
|     o o.        |
|   =o.+.         |
|. =++..          |
|o=++.            |

You now have a public and private key that you can use to authenticate. The next step is to place the public key on your server so that you can use SSH-key-based authentication to log in.

Login to VM

Switch to root

sudo su

Create Home Directory + .ssh Directory

mkdir -p /home/mynewuser/.ssh

Create Authorized Keys File

touch /home/mynewuser/.ssh/authorized_keys

Create User + Set Home Directory

useradd -d /home/mynewuser mynewuser

Add User to sudo Group

usermod -aG sudo mynewuser

Set Permissions

chown -R mynewuser:mynewuser /home/mynewuser/
chown root:root /home/mynewuser
chmod 700 /home/mynewuser/.ssh
chmod 644 /home/mynewuser/.ssh/authorized_keys

Now can add the contents of your file to the end of the authorized_keys file

echo public_key_string >> ~/.ssh/authorized_keys

In the above command, substitute the public_key_string with the output from the cat ~/.ssh/ command that you executed on your local system. It should start with ssh-rsa AAAA….

These steps tested on **Ubuntu 16.04