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

ssh-agent

When I'm running Gnome, ssh-agent will run ssh-add upon slogin/ssh if the identity is not loaded. I want to mimic this behavior on remote shells, but everything I find suggests to run ssh-add upon login. I only want to run ssh-add if I subsequently run slogin/ssh on the remote shell, not every time I login.

Best Answer

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 $@
}