Doing an ssh-add upon ssh/slogin if key is not in ssh-agent?

I worked out a solution for this via the bash shell.

Add to .bashrc:

check-ssh-add() {
if [ "$DESKTOP_SESSION" == "" ]; then
  if [[ `ssh-add -l` != *id_?sa* ]]; then 
    ssh-add -t 5h  ## 5 hour ssh-agent expiration
  fi
fi
}

slogin() {
check-ssh-add
/usr/bin/slogin $@
}

ssh() {
check-ssh-add
/usr/bin/ssh $@
}

scp() {
check-ssh-add
/usr/bin/scp $@
}

sftp() {
check-ssh-add
/usr/bin/sftp $@
}

There's actually an even simpler way. ssh-add -l returns true (0) if there are keys and false (1) otherwise, so your first function can be replaced with this:

check-ssh-add() {
  if ! ssh-add -l >/dev/null; then
      ssh-add -t 5h
  fi
}

 

Tags:

Ssh Agent