I was trying to solve this problem as I was generating keypairs and storing them in a database with Python. Below are some of the steps that I ended up using, namely starting
ssh-agent and interacting with it. It's in Python, but presumably you could translate it to whatever else. Another feature is that none of these use
shell=True, so they're safer from injection attacks.
sockfile = '/some/place.sock'
agent = subprocess.Popen(['ssh-agent',
'-D', # foreground mode
'-a', sockfile, # bind address (socket file)
'-D', # delete all identities from the agent
That fires up an
ssh-agent that's just for our program and clears it out (I believe it is loading my user keys into it, not sure though.) The environment variable
SSH_AUTH_SOCK ordinarily set by
ssh-agent (but that we did manually), we're feeding to other programs.
Next we use
ssh-add to feed it the private key (here it's stored in
dr.private_key as a string, but I need to serialize it, so I encode it as ASCII).
adder = subprocess.Popen(['ssh-add',
'-', # read key from stdin
retval = adder.wait()
assert retval == 0 # added successfully
Now whenever I use some SSH-using application, e.g. Git, I refer it to use the same SSH agent socket:
gitp = subprocess.Popen(
['git', '-C', os.path.abspath('../some-repo') ,'fetch'],
and it works just fine. The only "temporary file" is the socket used by
ssh-agent, but it's created so only the owner has permissions to it, and it's removed when you terminate the agent.