1 min read

SSH-Agent - How to protect your ssh key without typing its password non-stop

Not securing your key could lead to access problems if your key were to leak.

Adding a password to your key would force you to type it each time, that's why you haven't done so.

Well it doesn't have to be this way.

I named: SSH Agents (not it has nothing to do with AI agents)

SSH Agents loads your private key "in memory" so that it can be used without typing the password each time while still storing the key encrypted on your hard drive.

The only-ish risk you'd have is to leave your computer unlocked and unattended – but you wouldn't do that

  1. Add a password to your key
ssh -p -f <private_key>

  1. Make sure ssh-agent is runing

On most Linux systems, ssh-agent is automatically configured and run at login, and no additional actions are required to use it

If ssh-agent is not automatically started at login, it can be started manually with the command

eval `ssh-agent`

  1. Add keys to your agent

By default, the agent uses SSH keys stored in your ~/.ssh folder.

Use ssh-add will try to load your default ssh key ~/.ssh/id_rsa.

You can use ssh-add <key> to load other keys.

Use ssh-add -l to check which keys were loaded.

  1. Enjoy

  1. If you are having trouble

Add this to your ~/.zshrc or ~/.bashrc

env=~/.ssh/agent.env

agent_load_env () { test -f "$env" && . "$env" >| /dev/null ; }

agent_start () {
    (umask 077; ssh-agent >| "$env")
    . "$env" >| /dev/null ; }

agent_load_env

# agent_run_state: 0=agent running w/ key; 1=agent w/o key; 2=agent not running
agent_run_state=$(ssh-add -l >| /dev/null 2>&1; echo $?)

if [ ! "$SSH_AUTH_SOCK" ] || [ $agent_run_state = 2 ]; then
    agent_start
    ssh-add
elif [ "$SSH_AUTH_SOCK" ] && [ $agent_run_state = 1 ]; then
    ssh-add
fi

unset env