Skip to content

Instantly share code, notes, and snippets.

@kimw
Last active October 9, 2016 06:31
Show Gist options
  • Save kimw/d37eeaba09d44fae27607701abf53e59 to your computer and use it in GitHub Desktop.
Save kimw/d37eeaba09d44fae27607701abf53e59 to your computer and use it in GitHub Desktop.
Auto Keep SSH Passphrase In A Login Duration

Auto Keep SSH Passphrase In A Login Duration

The Goal

As descripted in the title, I just want a ssh passphrase keeper to:

  1. Keep the passphrase that I typed in a duration, e.g. 10 mins.
  2. Keep the passphrase til I logout even the duration is not reached.

So, I have operated 2 scripts, ~/.zshrc and ~/.zlogout, as follow.

cat <<"EOF" >>~/.zlogout

# remove all ssh passphrases at the last login is logout
if [ "$SSH_AGENT_LIFE_TIME" != "0" ]; then
    logins=$(w -ih $(whoami) | wc -l)
    [ $logins -eq 1 ] && ssh-add -D
fi
EOF
cat <<"EOF" >>~/.zshrc

# keep ssh passphrase during login for 10 mins
SSH_AGENT_LIFE_TIME=600  # 600 sec, 10 min
agent_env=$HOME/.ssh/agent_env
test -f $agent_env && . $agent_env >|/dev/null
agent_start() {
    test -d $HOME/.ssh || mkdir $HOME/.ssh
    (umask 077; ssh-agent -t $SSH_AGENT_LIFE_TIME >|$agent_env)
    . $agent_env >|/dev/null; }
add_key() {
    local ssh_majorver=$(ssh -V 2>&1 | cut -c 9)
    local ssh_minorver=$(ssh -V 2>&1 | cut -c 11)
    if [ $ssh_majorver -ge 7 ] && [ $ssh_minorver -ge 2 ]; then
        # 'AddKeysToAgent' is supported in OpenSSH 7.2+, we add keys at
        # the first time we use it.
        test -d $HOME/.ssh || mkdir $HOME/.ssh
        test -f $HOME/.ssh/config || touch $HOME/.ssh/config
        sed -i 's/^\(\s*AddKeysToAgent\s\+\(confirm\|ask\|no\)\s*\)$/#\1/' \
            ~/.ssh/config
        grep '^\s*AddKeysToAgent\s\+yes\s*$' $HOME/.ssh/config >/dev/null  \
            2>&1 || sed -i '1i\AddKeysToAgent yes\n' $HOME/.ssh/config
    else
        # OpenSSH < 7.2, add keys at login
        ssh-add
    fi; }
agent_run_state=$(ssh-add -l >|/dev/null 2>&1; echo $?)
case $agent_run_state in
    # agent_run_state=0: agent running w/ key
    0) ;; # do nothing
    # agent_run_state=1: agent w/o key
    1) [ "$SSH_AUTH_SOCK" ] && add_key ;;
    # agent_run_state=2: agent not running
    2) agent_start ; add_key ;;
esac
unset agent_env
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment