Server gets killed due to increasing number of ssh-agent processes

To kill the ssh-agent process, you can just simply use the ssh-agent -k command.

However, you might get the following error message:

SSH_AGENT_PID not set, cannot kill agent

It's related to the subshell that invoked by your command within parentheses. The parent shell can't see the variables that were generated in the subshell, making the SSH_AGENT_PID empty.

You can change the one-liner into:

ps -u $(whoami) | grep ssh-agent &> /dev/null
if [ $? -ne 0 ];then
    eval $(ssh-agent)
    ssh-add
fi
trap 'ssh-agent -k; exit' 0

The last line will kill the agent for you when you log out the system.

But please note that this only works with one session, let's say, if you login with second session, then the second session won't be blessed by the ssh-agent that you authorized in the first session. You will need to workaround it by exporting the SSH_AGENT_PID and SSH_AUTH_SOCK in the second session to make it work. You can do it by printing these two variable into a temporary file, and load it in .bashrc, a quick example:

ps -u $(whoami) | grep ssh-agent &> /dev/null
if [ $? -ne 0 ];then
    eval $(ssh-agent)
    ssh-add
    echo "export SSH_AGENT_PID=$SSH_AGENT_PID" > ~/.agent-profile
    echo "export SSH_AUTH_SOCK=$SSH_AUTH_SOCK" >> ~/.agent-profile
else
    source ~/.agent-profile
fi
trap 'ssh-agent -k; exit' 0

Have fun.

Edit:
Don't forget to kill all your ssh-agents before you try this in your .bashrc, otherwise it will fail to call ssh-agent as there is already a running one.

Tags:

Ssh

Server