Welcome, guest | Sign In | My Account | Store | Cart

If your python script may need to start an ssh-agent, this script sets up the environment according to the bourne-shell commands returned from that command on stdout.

Python, 8 lines
1
2
3
4
5
6
7
8
import os
import re

def ssh_attach(ssh_agent_cmd):
    sh_cmds=os.popen(ssh_agent_cmd).readlines()
    for sh_line in sh_cmds:
        matches=re.search("(\S+)\=(\S+)\;", sh_line)
        os.environ[matches.group(1)]=matches.group(2)

I have some test control scripts that start ssh sessions all over the place. Normally, my PuTTY agent on my PC forwards its authentication to these machines. Instead of running ssh-agent, one can use scripts like that at http://www.hackinglinuxexposed.com/tools/find-ssh-agent/src/find-ssh-agent to attach to an existing ssh agent.

1 comment

Gareth Latty 9 years, 10 months ago  # | flag

Note that I had a line that did not match the format, and so this throws an error (AttributeError: 'NoneType' object has no attribute 'group') with no matches.

To fix this, simply test matches:

import os
import re

def ssh_attach(ssh_agent_cmd):
    sh_cmds=os.popen(ssh_agent_cmd).readlines()
    for sh_line in sh_cmds:
        matches=re.search("(\S+)\=(\S+)\;", sh_line)
        if matches:
            os.environ[matches.group(1)]=matches.group(2)
Created by Andrew MacCormack on Tue, 9 Oct 2007 (PSF)
Python recipes (4591)
Andrew MacCormack's recipes (1)

Required Modules

Other Information and Tasks