SSH login via key file
Steps to enable SSH login via key file
1. Create public and private key pair on your local machine
- in folder
~/.ssh
- preferably in a sub-folder, as too many keys in
~/.ssh
might cause too many failed authentication tries when the system does key auto-selection
ssh-keygen -t rsa -b 4096
- you can leave the passphrase blank (not a good idea if the remote server is on the public Internet)
- or enter a secure passphrase that you will be prompted for at every login
2. Add public key to authorized keys on remote machine
- add the public to
~/.ssh/authorized_key
in the home directory of the related user - by either copy & pasting directly in
~/.ssh/authorized_keys
vi ~/.ssh/authorized_keys
- or by uploading only the public key to the remote machine and running the following command
cat key.pub >> ~/.ssh/authorized_keys
3. Login from local machine using the key
ssh user@example.com -i /.ssh/keyfile
Additional considerations
Remote machine must allow public key authentication
- to enable public key authentication on the remote machine edit the server configuration
/etc/ssh/sshd_config
- and set the
PubKeyAuthentication
parameter toyes
PubKeyAuthentication yes
- then restart the ssh daemon
systemctl restart sshd
Disable password authentication on remote machine
After you have tested public key authentication you might want to disable password authentication on the server for added security – especially on servers on the public Internet.
Caution!
Only do that after you verified that public key authentication is working correctly.
PasswordAuthentication no
Persist authentication method preference in your ssh client configuration
To make command line logins easier you can persist your authentication method preference in your ssh client configuration.
Edit your ~/.ssh/config
and create a new entry:
Host remote-machine
HostName 192.168.0.1
User=your_user
PubKeyAuthentication=yes
IdentityFile ~/.ssh/subfolder/key_file
Then you can type the following short command to log into your remote machine as user your_user
ssh remote-machine