wipe_removed_sockets() { # cleanup old agent-sockets if [ -r "${HOME}/.ssh-agent-forwarding" ]; then TMPFILE=$(mktemp) cut -d" " -f2 "${HOME}/.ssh-agent-forwarding" | \ xargs ls -a 2>/dev/null | \ grep -f - "${HOME}/.ssh-agent-forwarding" | \ sort -n > "${TMPFILE}" mv "${TMPFILE}" "${HOME}/.ssh-agent-forwarding" fi } fixssh() { # if the symlinked socket, does not exists # find latest connection, that is still alive wipe_removed_sockets if [ ! -e "${HOME}/.ssh-agent-forwarded-sock" ]; then LATEST_SOCK=$(tail -n 1 "${HOME}/.ssh-agent-forwarding" | cut -d" " -f2) if [ -n "$LATEST_SOCK" ]; then ln -sf "${LATEST_SOCK}" "${HOME}/.ssh-agent-forwarded-sock" fi fi } wipe_removed_sockets # if this login is via ssh and ssh-agent is forwarded if [ -n "$SSH_AUTH_SOCK" -a -n "$SSH_CLIENT" -a "$SSH_AUTH_SOCK" != "${HOME}/.ssh-agent-forwarded-sock" ]; then # add current socket echo "$(date +%s) $SSH_AUTH_SOCK $SSH_CLIENT" >> "${HOME}/.ssh-agent-forwarding" # remove old symlink if [ -L "${HOME}/.ssh-agent-forwarded-sock" ]; then rm -f "${HOME}/.ssh-agent-forwarded-sock" fi # create static symlink to socket if [ ! -e "${HOME}/.ssh-agent-forwarded-sock" ]; then ln -sf "$SSH_AUTH_SOCK" "${HOME}/.ssh-agent-forwarded-sock" else echo "Warning: ${HOME}/.ssh-agent-forwarded-sock exists and is not a symlink!" fi fi # if ssh auth sock not exists and the symlink exists # change $SSH_AUTH_SOCK to the symlink if [ ! -e "$SSH_AUTH_SOCK" -a -e "${HOME}/.ssh-agent-forwarded-sock" ]; then SSH_AUTH_SOCK="${HOME}/.ssh-agent-forwarded-sock" fi export SSH_AUTH_SOCK