2

I'm having a lot of trouble passing a string to the openssl commandline tool via python's subprocess like this:

process = subprocess.Popen(
    ["openssl", "rsa", "-in", pathFile, "-out", "id_rsa.out"],
    stdin = subprocess.PIPE,
    stdout = subprocess.PIPE,
    stderr = subprocess.PIPE,
    shell=False
)
try:
    process.communicate("some passphrase\n", timeout=2)
except:
    process.kill() #openssl stays alive otherwise.

The code above times out (with and without the std redirection in the Popen). I can use openssl normally through the terminal just fine, but I really need to be able to run this as part of my python script.

Any help would be appreciated.

DiscoStu
  • 559
  • 6
  • 15
  • 2
    read the first reason on: [Why not just use a pipe (popen())?](http://pexpect.readthedocs.org/en/stable/FAQ.html#whynotpipe). Find command-line switch that woud allow to avoid passing the passphrase via tty, or [use `pexpect` or `pty.openpty()`](http://stackoverflow.com/a/12471855/4279) – jfs Nov 04 '15 at 21:58
  • That's a good read. Thanks. – DiscoStu Nov 05 '15 at 09:17

1 Answers1

4

The section PASS PHRASE ARGUMENTS on the openssl man page explains how the passphrase input mechanism works. To make your example work, you should tell openssl to take the passphrase from stdin. Using your example as a starting point, the following works for me:

process = subprocess.Popen(
    ["openssl", "rsa", "-in", pathFile, "-out", "id_rsa.out", "-passin", "stdin"],
    stdin = subprocess.PIPE,
    stdout = subprocess.PIPE,
    stderr = subprocess.PIPE,
    shell=False
)
process.communicate("passphrase\n")
Reinier Torenbeek
  • 16,669
  • 7
  • 46
  • 69