When it comes to working with your servers (or any remote machine for that matter), public key encryption is a must. The basics are: you register a public key on the server-side and then use your private key to authenticate with the remote machine.
So you’ve generated a new SSH keypair or you have your existing SSH keys in the form of id_rsa or whatever. Now you want to push them to your remote server so you can use your private key to login?
cat ~/.ssh/id_rsa.pub | ssh <user>@<hostname> 'cat >> .ssh/authorized_keys && echo "Public key successfully copied"'
You of course will want to replace
<hostname> with their appropriate values and supply any other required values.
You should never copy and paste shell commands off of the internet, so lets quickly explain what the above code does. We actually are calling multiple commands one after the other, rather than one method that does everything for us.
- cat ~/.ssh/id_rsa.pub — The concatenate command can do many things, but here we are simply concatenating the contents of our public key and then it is returned to the terminal window
- | — We then pipe the returned contents of our public key file to an ssh call
@ — This is where we connect to our remote machine where we want to save the key
- cat >> .ssh/authorized_keys — Assuming everything went okay, we then use cat command to store the piped contents of our public key into the authorized_keys file