Generating an SSH Key and Copying it to Remote Server
August 26, 2014
code
mkdir ~/.ssh && chmod 700 ~/.ssh
touch ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys
# copy key.pub to authorized_keys
# nano /etc/ssh/sshd_config
service ssh reload
Generate the Key (on local server)
code
cd ~/.ssh && ssh-keygen -t ed25519
Ed25519 is a newer algorithm which is faster than RSA. Ed25519 is supported by OpenSSH so you should be good in almost all cases. Github recommends passing it your email with -C which is then uses as a label.
code
cd ~/.ssh && ssh-keygen -t ed25519 -C "hello@example.com"
Add SSH key to macOS Keychain
code
ssh-add --apple-use-keychain ~/.ssh/id_ed25519
Making Sure the Remote Server Accepts SSH Keys
view the server's sshd_config file
code
cat /etc/ssh/sshd_config
Check the following:
code
RSAAuthentication yes
PubkeyAuthentication yes
AuthorizedKeysFile ~/.ssh/authorized_keys
Making sure the .ssh folder and authorized_keys file exists on Remote server
code
sudo mkdir ~/.ssh && sudo touch ~/.sh/authorized_keys
Setting Permission on Remote Server
code
sudo chmod go-w ~/ && sudo chmod 700 ~/.ssh && sudo chmod 600 ~/.ssh/authorized_keys
Copying SSH Public Key from Local to Remote Server
On macOS you can use the ssh-copy-id command to copy the SSH key to remote server
code
ssh-copy-id -i ~/.ssh/mykey user@host
If you get the following error
code
/usr/bin/ssh-copy-id: WARNING: All keys were skipped because they already exist on the remote system.
(if you think this is a mistake, you may want to use -f option)
then force copy it with -f flag
code
ssh-copy-id -f -i <key_path> <remote_server>
Remote server can either be in the user@host form or a name of a saved Host in .ssh/config
Alternatively, you can copy the key output manually over SSH, like this:
code
cat ~/.ssh/id_ed25519.pub | ssh username@example.com "cat >> ~/.ssh/authorized_keys"
replace id_ed25519.pub with your generated key.
Troubleshooting
- make sure the authorized_keys file isn't empty.
- make sure you copied the correct authorized_keys file (.pub file that is)
- make sure the user you are connecting to owns the .ssh folder and the authorized_keys file
- make sure the permissions for the .ssh (700) folder and the authorized_keys (600) file are correct on the remote server
- make sure the path given in 'sshd_config' is correct.
/home/.ssh/authorized_keysand~/.ssh/authorized_keysare different if the user you are connecting to isn't root.~/.ssh/authorized_keysis preferred since it is relative to the user.