Skip to content

Instantly share code, notes, and snippets.

@mumoshu
Last active March 26, 2018 09:01
Show Gist options
  • Save mumoshu/bdac8b3d03f2eb4a95c7bdf2b739a115 to your computer and use it in GitHub Desktop.
Save mumoshu/bdac8b3d03f2eb4a95c7bdf2b739a115 to your computer and use it in GitHub Desktop.
Runs an arbitrary command within a bash session in which a temporary ssh-agent is running
$ DEBUG=1 ./vaulted-bash.sh bash
Starting ssh-agent...
Started ssh-agent
Type path to ssh key. Blank to continue> /Users/example/.ssh/id_rsa
Identity added: /Users/example/.ssh/id_rsa (/Users/example/.ssh/id_rsa)
Type path to ssh key. Blank to continue>
bash-3.2$ ssh-add -l
4096 SHA256:PXeBU/YU3qFCpTIQvE5HHVwa8tnaftJzgNukHswTJrc /Users/example/.ssh/id_rsa (RSA)
bash-3.2$ exit
exit
Stopped ssh-agent(80564)
# Place this in your .bash_profile for interactive-only support,
# or in .bashrc for interactive and non-interactive support.
#
# See: https://confluence.atlassian.com/display/BITBUCKET/Set+up+SSH+for+Git#SetupSSHforGit-installpublickey
SSH_ENV="$HOME/.ssh/environment"
debug() {
if [ ! -z "$DEBUG" ]; then
echo "$1"
fi
}
on_exit() {
:
}
before_exit() {
debug "Stopping ssh-agent($SSH_AGENT_PID)"
kill $SSH_AGENT_PID
while ps -p $SSH_AGENT_PID >/dev/null; do
debug "."
sleep 1
done
debug "Stopped ssh-agent($SSH_AGENT_PID)"
exit 2
}
trap on_exit EXIT # EXIT = 0
trap before_exit HUP INT QUIT TERM STOP # 1 2 3 15
# start the ssh-agent
function start_agent {
debug "Starting ssh-agent..."
# spawn ssh-agent
ssh-agent | sed 's/^echo/#echo/' > "$SSH_ENV"
debug "Started ssh-agent"
chmod 600 "$SSH_ENV"
. "$SSH_ENV" > /dev/null
while debug "Type path to ssh key. Blank to continue> " && read SSH_KEY; do
if [ -z "$SSH_KEY" ]; then
break
fi
msg=$(ssh-add $SSH_KEY 2>&1)
debug "$msg"
done
}
# test for identities
function test_identities {
ssh-add -l | grep "The agent has no identities" > /dev/null
}
# check for running ssh-agent with proper $SSH_AGENT_PID
if [ -n "$SSH_AGENT_PID" ]; then
ps -ef | grep "$SSH_AGENT_PID" | grep ssh-agent > /dev/null
if [ $? -eq 0 ]; then
test_identities
fi
# if $SSH_AGENT_PID is not properly set, we might be able to load one from
# $SSH_ENV
else
unset SSH_AUTH_SOCK
unset SSH_AGENT_PID
start_agent
test_identities
fi
"$@"
# For handling Ctrl-D (if `stty -a` outputs `eof = ^D`)
before_exit
#!/usr/bin/env bash
# Usage:
# $ mkfifo p1
# $ SSH_KEYS=p1 ./vaulted-bash-2.sh
# # In another shell:
# $ echo $HOME/.ssh/id_rsa $another_key > p1
# $ ls p1 # not found
set -e
if [ -z "$SSH_KEYS" ]; then
echo "SSH_KEYS must not be empty" 1>&2
exit 2
fi
cleanup() {
if [ -e "$SSH_KEYS" ]; then
rm "$SSH_KEYS"
fi
exit 2
}
trap cleanup EXIT
ssh-agent bash -ic 'while read path; do echo $path && ssh-add $path; done <"$SSH_KEYS" && rm "$SSH_KEYS" && bash'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment