Skip to content

Instantly share code, notes, and snippets.

@feldim2425
Created October 29, 2019 12:50
Show Gist options
  • Save feldim2425/19eab0b6f525a105c29b7aea063baf6b to your computer and use it in GitHub Desktop.
Save feldim2425/19eab0b6f525a105c29b7aea063baf6b to your computer and use it in GitHub Desktop.
#!/bin/bash
# Author: FeldiM2425
# Licence: MIT
# Description:
# This Bashscript is used to detect the ssh-agent
# on a specific Unix-Socket (defined by the SSH_AUTH_SOCK environment variable)
# and start it when the ssh-agent is not running. If "-f" is passed as argument
# the socket file will be deleted before the ssh-agent is started even if a ssh-agent
# was detectet. The agent WILL NOT GET shut down before this operation
# If "-f" is not passed the script will only delete the socket file when no agent is listening
# on that socket. In case the socket file is missing, the agent simply gets started.
#
# Usage:
# $ ./start_sshAgent.sh ... starts the ssh agent with the given socket file
# $ ./start_sshAgent.sh -f ... force deleting the socket before starting the ssh-agent
FORCE=false
while getopts f opt
do
case $opt in
f) FORCE=true;;
esac
done
# When the socket already exists we might want to delete the socket
if [ -e "$SSH_AUTH_SOCK" ] ; then
echo "Existing socket detected"
# Check all programs listening on the $SSH_AUTH_SOCK unix-socket
# When no program is listening it is safe to delete the socket
if (( $(ss -Hax state listening src $SSH_AUTH_SOCK | wc -l) < 1 ))
then
echo "No ssh-agent detected on the socket"
FORCE=true
fi
if [ $FORCE = true ]
then
echo "Deleting socket file at \"$SSH_AUTH_SOCK\""
rm $SSH_AUTH_SOCK
fi
fi
# When the socket doesn't exist (either by deleting it in this script or it didn't exist)
# the ssh-agent can be started on that socket, otherwise just a information is printed
if [ ! -e "$SSH_AUTH_SOCK" ] ; then
echo "Start SSH-Agent..."
ssh-agent -a "$SSH_AUTH_SOCK" >/dev/null
ssh-add 2>/dev/null >/dev/null # This line adds the ~/.ssh/id_rsa key
else
echo "Socket file at \"$SSH_AUTH_SOCK\" already exists!"
echo "Run this script again with -f or delete the socket file first!"
fi
echo "Finished"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment