Created
May 6, 2026 20:31
-
-
Save alisade/2d5f0f0e45f9d02793ce20492ecf9a32 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| # This is a small script to generate a reusable ssh-agent for use with ssh key forwarding | |
| # The classic use-case is to do git pull on a remote server without sending your ssh keys | |
| # export SSH_AUTH_SOCK="$(sagent)" | |
| # ssh -A remoteserver.com | |
| # git pull | |
| # | |
| # It will helpfully re-use any existing ssh-agent processes, so you dont need to worry about spawning | |
| # too many. It will only ever spawn a new ssh-agent process if needed. | |
| # | |
| # This script can be called in one of two ways: | |
| # 1. export SSH_AUTH_SOCK="$(sagent)" | |
| # 2. source /path/to/sagent | |
| function sshagent_findsockets { | |
| find /tmp -uid $(id -u) -type s -name agent.\* 2>/dev/null | |
| } | |
| function sshagent_testsocket { | |
| if [ ! -x "$(which ssh-add)" ] ; then | |
| echo "ssh-add is not available; agent testing aborted" | |
| return 1 | |
| fi | |
| if [ X"$1" != X ] ; then | |
| export SSH_AUTH_SOCK=$1 | |
| fi | |
| if [ X"$SSH_AUTH_SOCK" = X ] ; then | |
| return 2 | |
| fi | |
| if [ -S $SSH_AUTH_SOCK ] ; then | |
| ssh-add -l > /dev/null | |
| if [ $? != 0 -a $? != 1 ] ; then | |
| echo "Socket $SSH_AUTH_SOCK is dead! Deleting!" | |
| rm -f $SSH_AUTH_SOCK | |
| return 4 | |
| else | |
| return 0 | |
| fi | |
| else | |
| echo "$SSH_AUTH_SOCK is not a socket!" | |
| return 3 | |
| fi | |
| } | |
| function sshagent_init { | |
| # ssh agent sockets can be attached to a ssh daemon process or an | |
| # ssh-agent process. | |
| AGENTFOUND=0 | |
| # Attempt to find and use the ssh-agent in the current environment | |
| if sshagent_testsocket ; then AGENTFOUND=1 ; fi | |
| # If there is no agent in the environment, search /tmp for | |
| # possible agents to reuse before starting a fresh ssh-agent | |
| # process. | |
| if [ $AGENTFOUND = 0 ] ; then | |
| for agentsocket in $(sshagent_findsockets) ; do | |
| if [ $AGENTFOUND != 0 ] ; then break ; fi | |
| if sshagent_testsocket $agentsocket ; then AGENTFOUND=1 ; fi | |
| done | |
| fi | |
| # If at this point we still haven't located an agent, it's time to | |
| # start a new one | |
| if [ $AGENTFOUND = 0 ] ; then | |
| eval `ssh-agent` | |
| fi | |
| # Clean up | |
| unset AGENTFOUND | |
| unset agentsocket | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment