Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

The back story -- I've been using Git on this computer (Windows XP) for about 8 months with no problem. Suddenly, last week, it is no longer asking me for my username and password when I start Git up.

It is asking every time I try to touch my remote branches, and considering I have a passphrase rather than a password it is really annoying.

I am using the code from GitHub in my .profile file:

SSH_ENV="$HOME/.ssh/environment"

# start the ssh-agent
function start_agent {
    echo "Initializing new SSH agent..."
    # spawn ssh-agent
    ssh-agent | sed 's/^echo/#echo/' > "$SSH_ENV"
    echo succeeded
    chmod 600 "$SSH_ENV"
    . "$SSH_ENV" > /dev/null
    ssh-add
}

# test for identities
function test_identities {
    # test whether standard identities have been added to the agent already
    ssh-add -l | grep "The agent has no identities" > /dev/null
    if [ $? -eq 0 ]; then
        ssh-add
        # $SSH_AUTH_SOCK broken so we start a new proper agent
        if [ $? -eq 2 ];then
            start_agent
        fi
    fi
}

# 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
    if [ -f "$SSH_ENV" ]; then
  . "$SSH_ENV" > /dev/null
    fi
    ps -ef | grep "$SSH_AGENT_PID" | grep ssh-agent > /dev/null
    if [ $? -eq 0 ]; then
        test_identities
    else
        start_agent
    fi
fi

The line that is catching it is:

if [ -n "$SSH_AGENT_PID" ]; then

It thinks it's a valid entry. Needless to say, I've restarted and relogged onto my computer in many different ways, always the same. I've echoed out the process ID and it isn't a running process on my computer (per Task Manager).

I am have upgraded my Git (hoping it would fix the problem) and I am now running version 1.7.11-preview20120620

Any help would be greatly appreciated.

share|improve this question
up vote 7 down vote accepted

How about simplifying it a bit?

agent_running() {
    [ "$SSH_AUTH_SOCK" ] && { ssh-add -l >/dev/null 2>&1 || [ $? -eq 1 ]; }
}

env=~/.ssh/agent.env

if ! agent_running && [ -s "$env" ]; then
    . "$env" >/dev/null
fi

if ! agent_running; then
    ssh-agent >"$env"
    . "$env" >/dev/null
    ssh-add
fi

unset env
share|improve this answer
    
Nice! Works like a charm! – Kerry Jones Jun 26 '12 at 19:46
    
Excellent! This Works on win XP! Totally different to the one in this tute, obviously the tute has wrong code for windows: the $HOME has spaces in it and this isn't allowed and can't be manually excaped (I tried). – user233105 Jun 23 '13 at 4:17
    
@Bezz: It can certainly be quoted: . "$HOME/.ssh/env" or . "$SSH_ENV" – grawity Jun 23 '13 at 13:45

Python version of the script. Tested on Windows Vista + Git SSH tools. From here.

#!/usr/bin/env python
"""\
ssh agent wrapper to detect or run agent, set environment
and either show it or execute specified command in this
environment.

usage: ssh-agent.py
       ssh-agent.py <command>

examples:
    ssh-agent.py ssh-add
    ssh-agent.py ssh -A user@host
"""

"""
[x] no agent is running
  [x] run agent

[x] agent is running
  [x] set environment
  [x] show how to set environment manually

  [x] if there is command, run it
"""

__version__ = '1.0'
__author__  = 'anatoly techtonik <techtonik@gmail.com>'
__license__ = 'Public Domain'

import os
import sys

#--[inline shellrun 2.0 import run, run_capture]
import subprocess

class Result(object):
    def __init__(self, command=None, retcode=None, output=None):
        self.command = command or ''
        self.retcode = retcode
        self.output = output
        self.success = False
        if retcode == 0:
            self.success = True

def run(command):
    process = subprocess.Popen(command, shell=True)
    process.communicate()
    return Result(command=command, retcode=process.returncode)

def run_capture(command):
    outpipe = subprocess.PIPE
    process = subprocess.Popen(command, shell=True, stdout=outpipe,
                                                    stderr=outpipe)
    output, _ = process.communicate()
    return Result(command=command, retcode=process.returncode, output=output)
#--[/inline]


SSH_ENV = os.path.expanduser("~/.ssh/agent.env")


def detected():
    if 'SSH_AUTH_SOCK' not in os.environ:
        if os.path.exists(SSH_ENV):
            agentenv = parse()
            os.environ.update(agentenv)
        if 'SSH_AUTH_SOCK' not in os.environ:
            return False
    r = run_capture('ssh-add -L')
    if r.retcode == 0:    # has keys
        return True 
    elif r.retcode == 1:  # no keys
        return True
    elif r.retcode == 2:  # not running
        return False
    else:
        print(r.output)
        return False

def start():
    run('ssh-agent > "%s"' % SSH_ENV)

def parse():
    params = open(SSH_ENV, 'r').read()
    # SSH_AUTH_SOCK=/tmp/ssh-owYJTz7968/agent.7968; export SSH_AUTH_SOCK;
    # SSH_AGENT_PID=6284; export SSH_AGENT_PID;
    # echo Agent pid 6284;
    params = params.replace('; ', '\n')
    params = params.replace(';', '')
    result = dict()
    for line in params.splitlines():
        if '=' not in line:
            continue
        key, value = line.split('=')
        result[key] = value
    return result


def main():
    if '-h' in sys.argv or '--help' in sys.argv:
        sys.exit(__doc__)

    if not detected():
        print('..agent not detected, starting..')
        start()

    if not detected:
        sys.exit('error starting ssh-agent')
    else:
        if os.name == 'nt':
            print('@rem ..agent is running, set environment as:')
            for k,v in parse().items():
                print('set %s=%s' % (k,v))
        else:
            print('# ..agent is running, set environment as:')
            run('cat "%s"' % SSH_ENV)

        if sys.argv[1:]:
            run(sys.argv[1:])


if __name__ == '__main__':
    main()
share|improve this answer

In recent versions of Git for Windows 2.x, there is a start-ssh-agent.cmd which can be run in git bash and a cmd.

See also here: https://github.com/git-for-windows/git/wiki/Auto-launching-ssh-agent-when-git-starts

share|improve this answer

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .