SSH key-based authentication
Useful commands and snippets when dealing with Linux
2023-10-12
SSH Key
Create a new SSH key without a passphrase.
ssh-keygen -t rsa -b 4096
Copy the SSH key to the remote device you want to log in.
ssh-copy-id -i <ID_RSA> <USER@HOST>
SSH Config
Add the following snippet to your SSH config file which is located at ~/.ssh/config
. This links the host address with a specific private key.
Host <IP_ADDRESS>
User <USER>
IdentityFile ~/.ssh/<PRIVATE_KEY>
IdentitiesOnly yes
SSH Agent
Automatic start
Copy the following code snippet in your .bashrc
file.
This autostarts the SSH agent when you open a new shell.
function start_ssh_agent {
eval $(/usr/bin/ssh-agent) > /dev/null
/usr/bin/ssh-add ~/.ssh/<PRIVATE_KEY> 2> /dev/null
}
ps -ef | grep ${SSH_AGENT_PID} | grep ssh-agent$ > /dev/null || {
start_ssh_agent;
}
NOTE: This code snippet is still a bit buggy. Adding a private keys with a SSH config is a better approach.
Manual start
To start the SSH agent manually run the following to commands.
eval $(ssh-agent)
ssh-add ~/.ssh/<PRIVATE_KEY>
Stop the SSH agent
To stop the SSH agent lookup the PID and kill the process.
ps aux | grep ssh-agent
kill <SSH_AGENT_PID>