Coffee & Beer

Rantings and Ravings of the technical sort

Tmux + Ssh-agent

So I just wanted to get a quick one out there, before I forgot about this little hack I came up with.

Problem At work we’ve got a ssh key we use to get into most things. Its got a nice, beefy passphrase on it no one can remember, so the normal operating mode is to fire up ssh-agent, load the key (which involves some hackery since its owner by root and we need to laod it into user environments), and then connect with that key. I tend to operate out of a long running remote tmux session, so I wanted the abiloty to fire up tmux, load the key, and have ssh agent use that on any and all new windows I open within that tmux session. If I close the tmux session, sure, I need to relaod the key, but so long as I keep it open, I can come and go as I please and open/close windows while keeping the key loaded.

Solution So this involved a could hacky bits to get going.

First, in .tmux.conf I set:

1
2
set -g update-environment -r
setenv -g SSH_AUTH_SOCK $HOME/.ssh/ssh_auth_sock.$HOSTNAME

So, copy my environtment on new sssions, and, set an environment variable of SSH_AUTH_SOCK to $HOME/.ssh/ssh_auth_sock.$HOSTNAME. Thats because we’re going to force ssh-agent to use that when we load it up for the first time in a given tmux instance

In my .zshrc, I created a function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
sa () {
#if we have a pid AND are working
  if [ `pgrep -u $USER ssh-agent` ];then
    export SSH_AGENT_PID=`pgrep -u $USER ssh-agent`
    export SSH_AUTH_SOCK=$HOME/.ssh/ssh_auth_sock.$HOSTNAME
  else
    `ssh-agent -k`
    rm -rf $SSH_AUTH_SOCK
    unset SSH_AUTH_SOCK
    unset SSH_AGENT_PID
    export SSH_AUTH_SOCK=$HOME/.ssh/ssh_auth_sock.$HOSTNAME
    `killall -u $USER ssh-agent`
    ssh-agent -a $SSH_AUTH_SOCK -s
    export SSH_AGENT_PID=`pgrep -u $USER ssh-agent`
  fi
}

Told you it was hacky. Basically, if ssh-agent is already running, fix/make sure the env vars are set correctly. Otherwise, make sure ssh-agent is really dead, unset all its vars, sest them to what WE want, and fire it back up, forcing it to use them.

When starting a new tmux session, I run the sa function in the first window. Any windows after that will get those env vars and I get to keep my ssh-agent!

Bonus Per-host history

1
2
3
export HISTFILE="$HOME/.zsh_history_$HOSTNAME"
setopt inc_append_history
setopt share_history

Comments