ambakshi
9/10/2014 - 9:30 PM

ssh-agent

ssh-agent

#!/bin/bash

SSH_ENV="$HOME/.ssh/environment.$HOSTNAME"

start ()  {
    if [ -f "$SSH_ENV" ]; then
        source "$SSH_ENV"
        if kill -0 "$SSH_AGENT_PID" 2>/dev/null; then
            echo "Run 'source $SSH_ENV'" >&2
            return
        fi
        rm -f "$SSH_AUTH_SOCK"
    fi
    echo "Starting new ssh-agent" >&2
    /usr/bin/ssh-agent | sed 's/^echo/#echo/' > "$SSH_ENV"
    chmod 0600 "$SSH_ENV"
    source "$SSH_ENV" > /dev/null
    local key=
    for key in id_rsa id_rsa.root id_rsa.deploy; do
        /usr/bin/ssh-add $HOME/.ssh/$key
    done
    echo "Run 'source $SSH_ENV'"
}

stop () {
    if [ -f "$SSH_ENV" ]; then
        source "$SSH_ENV" > /dev/null
    fi
    ssh-agent -k >&2
    rm -f "$SSH_ENV" "$SSH_AUTH_SOCK"
}

if [ $# -eq 0 ]; then
    echo "$0 [start|stop]" >&2
    exit 1
fi

"$@"

#
# After running the above script, paste the following into your ~/.bash_profile or ~/.profile
#
if test -f "$HOME/.ssh/environment.$HOSTNAME"; then
    source "$HOME/.ssh/environment.$HOSTNAME"
    if ! test -e /proc/$SSH_AGENT_PID; then
        rm -f $HOME/.ssh/environment.$HOSTNAME
        unset SSH_AUTH_SOCK SSH_AGENT_PID
        echo >&2 "Run ~/bin/ssh-agent.sh to set your SSH env"
        echo >&2 "then source your profile to set the ssh-agent"
        echo >&2 "environment."
    fi
fi