Created
November 9, 2012 23:14
-
-
Save joemiller/4048941 to your computer and use it in GitHub Desktop.
ssh-agent handler for bashrc/profile
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# ~/.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 | |
################# |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment