Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save abhijeetchopra/a93d477fbd1f71a0b967fb262c66cf79 to your computer and use it in GitHub Desktop.

Select an option

Save abhijeetchopra/a93d477fbd1f71a0b967fb262c66cf79 to your computer and use it in GitHub Desktop.

Revisions

  1. @joemiller joemiller created this gist Nov 9, 2012.
    76 changes: 76 additions & 0 deletions gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,76 @@
    # ~/.profile, ~/.bashrc, (or ~/.bash_profile in cygwin and others)
    ##########
    ## joe miller, ssh-agent handling stuff
    ##
    SSH_ENV="$HOME/.ssh/environment"

    SSH_KEY_PRIVATE="$HOME/.ssh/id_rsa"
    SSH_KEY_PUB="$HOME/.ssh/id_rsa.pub"

    function start-agent {
    SSH_ENV=${SSH_ENV:-"$HOME/.ssh/environment"}

    if [ -f "${SSH_ENV}" ]; then
    . "${SSH_ENV}" > /dev/null
    #ps ${SSH_AGENT_PID} doesnt work under cywgin
    ps -ef | grep ${SSH_AGENT_PID} | grep ssh-agent$ > /dev/null || {
    _start_agent;
    }
    else
    _start_agent;
    fi
    }

    function _start_agent {
    SSH_ENV=${SSH_ENV:-"$HOME/.ssh/environment"}

    echo "Initialising new SSH agent..."
    /usr/bin/ssh-agent | sed 's/^echo/#echo/' > "${SSH_ENV}"
    echo succeeded
    chmod 600 "${SSH_ENV}"
    . "${SSH_ENV}" > /dev/null
    ssh-add ${SSH_KEY_PRIVATE}
    }

    function stop-agent {
    SSH_ENV=${SSH_ENV:-"$HOME/.ssh/environment"}

    echo "Killing SSH-agent..."
    chmod 600 "${SSH_ENV}"
    . "${SSH_ENV}" > /dev/null
    eval `ssh-agent -k`
    }

    function put-ssh-key {
    SSH_ENV=${SSH_ENV:-"$HOME/.ssh/environment"}

    _host=$1
    _user=${2:-${USER}}
    _port=${3:-22}

    if [ -z ${_host} ] || [ -z ${_user} ] || [ -z ${_port} ]; then
    echo "Usage: put-ssh-key hostname [username] [port]"
    echo
    echo "username and port are optional, but if you include"
    echo "one you must include both"
    return 1
    fi

    pub_key_data=`cat ${SSH_KEY_PUB}`

    ssh -p ${_port} ${_user}@${_host} "mkdir -p ~${_user}/.ssh ; \
    touch ~${_user}/.ssh/authorized_keys ; \
    chmod 0700 ~${_user}/.ssh ; \
    chmod 0600 ~${_user}/.ssh/authorized_keys ; \
    echo "${pub_key_data}" >>~${_user}/.ssh/authorized_keys ; "
    }

    # ensure an agent is available whenever ssh or scp is run
    alias ssh='start-agent ; ssh'
    alias scp='start-agent ; scp'

    # remove the line below if you want to delay the startup
    # of ssh-agent until the first time you use ssh
    start-agent

    #################