Auto SSH Agent
(2019-09-04)
Notes that probably won't make any sense to anyone other than myself. This is borderline incoherent and probably mostly wrong
~/bin/agent, everywhere:
This is a generic script for launching the agent on the keyhost. I'm using kageant on Windows right now as my keyhost so I don't actually use this.
#!/bin/bash
HOST=`hostname`
AGENT="ssh-agent -s"
if [ ! -d $HOME/.ssh/agent ]; then
mkdir -p $HOME/.ssh/agent
fi
pid=`ps -u$LOGNAME | grep ssh-age | awk '{print $1}'`
if [ -z "$pid" ]; then
$AGENT | grep -v echo > $HOME/.ssh/agent/$HOST & pid=$!
sleep 1 # Let it fork and stuff
fi
On The Keyhost
in .profile or .bash_profile:
~/bin/agent
. ~/.ssh/agent/`uname -n`
On the systems you are going to ssh from
(This can be the source and/or target systems if you are going to be stringing chains of ssh sessions together)
In .ssh/config:
ForwardAgent yes
On The Targets
In .bashrc:
if [ -S "$SSH_AUTH_SOCK" ] && [ ! -h "$SSH_AUTH_SOCK" ]; then
ln -sf "$SSH_AUTH_SOCK" ~/.ssh/agent/$(hostname)_ssh_auth_sock
fi
export SSH_AUTH_SOCK=~/.ssh/agent/$(hostname)_ssh_auth_sock
Use
- log into keyhost, ssh-agent starts
- use ssh-add to install your key into the running agent
- ssh as desired
- when you disconnect, any forwarded agent sockets become useless (while you are disconnected)
- when you return, ssh back in to the target, all agent forwarders on that host become active again
Commentary
As noted above, I'm using my Windows system(s) as keyhosts, so I use kageant with kitty for my initial ssh session. From there I land on hosts where screen sessions are run, and can ssh from there without requiring passwords (for the most part).
Credit
I started with this Superuser.com question.