Puttygen control with Popen
I am writing a python script to generate SSH keys for users. After generating them with ssh-keygen, I would like to use puttygen to generate a .ppk file. Unfortunately puttygen does not allow passphrases on the command line - so I am trying to pipe them to my stdin using popen. He always complains about the "wrong passphrase", but typing commands on the command line and typing in the passphrase works great there - the problem is something in my pop technique. puttygen asks for the passphrase three times - once to read the key generated by openssh and twice for the key for the new file. Puttygen reports an error after the first request, so the problem is trying to send the passphrase to the subprocess.
Ubuntu 11.10 platform, python 2.7, latest openssh and putty-tools packages. Here's a cut out script to illustrate the problem I'm running into:
#!/usr/bin/python import sys, os, subprocess KEYGEN = "/usr/bin/ssh-keygen -t rsa -b 4096 -f id_rsa -N passphrase" PUTTYGEN = "/usr/bin/puttygen id_rsa -P -O private -o test.ppk" phrase = "passphrase" try: os.unlink('id_rsa') except: pass try: os.unlink('id_rsa.pub') except: pass try: os.unlink('test.ppk') except: pass ## generate the public and private keys subprocess.call(KEYGEN.split(' ')) ## convert key to PuTTY format p = subprocess.Popen(PUTTYGEN.split(' '), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) ## Two techniques I've tried - also tried variations on CR/LF. No luck. if False: o, e = p.communicate(phrase + '\n' + phrase + '\n' + phrase + '\n') #o, e = p.communicate(phrase + '\r' + phrase + '\r' + phrase + '\r') #o, e = p.communicate(phrase + '\r\n' + phrase + '\r\n' + phrase + '\r\n') print o print e else: p.stdin.write(phrase + '\n') p.stdin.write(phrase + '\n') p.stdin.write(phrase + '\n') print p.stdout.read() print p.stderr.read() p.stdin.close() p.wait()
source to share