linuxbashshellssh

How to check if ssh-agent is already running in bash?


I have a sample sh script on my Linux environment, which basically run's the ssh-agent for the current shell, adds a key to it and runs two git commands:

#!/bin/bash
eval "$(ssh-agent -s)"
ssh-add /home/duvdevan/.ssh/id_rsa

git -C /var/www/duvdevan/ reset --hard origin/master
git -C /var/www/duvdevan/ pull origin master

Script actually works fine, but every time I run it I get a new process so I think it might become a performance issue and I might end up having useless processes out there.

An example of the output:

Agent pid 12109
Identity added: /home/duvdevan/.ssh/custom_rsa (rsa w/o comment)

Also, along with all this, is it possible to find an existing ssh-agent process and add my keys into it?


Solution

  • Also, along with all this, is it possible to find an existing ssh-agent process and add my keys into it?

    Yes. We can store the connection info in a file:

    # Ensure agent is running
    ssh-add -l &>/dev/null
    if [ "$?" == 2 ]; then
        # Could not open a connection to your authentication agent.
    
        # Load stored agent connection info.
        test -r ~/.ssh-agent && \
            eval "$(<~/.ssh-agent)" >/dev/null
    
        ssh-add -l &>/dev/null
        if [ "$?" == 2 ]; then
            # Start agent and store agent connection info.
            (umask 066; ssh-agent > ~/.ssh-agent)
            eval "$(<~/.ssh-agent)" >/dev/null
        fi
    fi
    
    # Load identities
    ssh-add -l &>/dev/null
    if [ "$?" == 1 ]; then
        # The agent has no identities.
        # Time to add one.
        ssh-add -t 4h
    fi
    

    This code is from pitfalls of ssh agents which describes both the pitfalls of what you're currently doing, of this approach, and how you should use ssh-ident to do this for you.


    If you only want to run ssh-agent if it's not running and do nothing otherwise:

    if [ $(ps ax | grep [s]sh-agent | wc -l) -gt 0 ] ; then
        echo "ssh-agent is already running"
    else
        eval $(ssh-agent -s)
        if [ "$(ssh-add -l)" == "The agent has no identities." ] ; then
            ssh-add ~/.ssh/id_rsa
        fi
    
        # Don't leave extra agents around: kill it on exit. You may not want this part.
        trap "ssh-agent -k" exit
    fi
    

    However, this doesn't ensure ssh-agent will be accessible (just because it's running doesn't mean we have $SSH_AGENT_PID for ssh-add to connect to).