0

In Perl, if I have execute a script and pass a password to it programatically, I would do this:

my $result = qx { "Calling some script which prompts for a user and  password" <<EOF
administrator
password
EOF
};

It executes the following while capturing its output:

/bin/sh -c ' "Calling some script which prompts for a user and  password" <<EOF
administrator
password
EOF
'

May I know the equivalent of this in Python?

ikegami
  • 367,544
  • 15
  • 269
  • 518
user1939168
  • 547
  • 5
  • 20
  • 3
    For us Python people: Please explain what this Perl code is doing. What is the expected behaviour? –  Jul 09 '15 at 11:37
  • 1
    `qx` is perl's "execute this" - it's identical to shell backticks. Runs the command and captures the _output_ in `$result`. – Sobrique Jul 09 '15 at 11:46
  • 2
    possible duplicate of [Equivalent of Backticks in Python](http://stackoverflow.com/questions/1410976/equivalent-of-backticks-in-python) – buff Jul 09 '15 at 11:49
  • @Sobrique Thanks. But how is the script in the question "pass a password"? –  Jul 09 '15 at 11:50
  • Don't know - I don't actually think that would work to pass a password to something anyway. Most things that take a password don't let you 'pipe' through them on `STDIN` in the first place. – Sobrique Jul 09 '15 at 11:52

1 Answers1

1

If I udnerstand your question correctly, you're trying to start an external script within its own process, and send that script some data - a password - via its standard input.

In Python, this is done using the subprocess module. This module runs external scripts and has a stdin, stdout and stderr parameters.

For example, suppose that the script is md5sum. You would like to send it the password secret:

>>> import subprocess as sp
>>> p = sp.Popen('md5sum', stdin=sp.PIPE, stdout=sp.PIPE, stderr=sp.PIPE)
>>> p.communicate(input="secret")                   # <-- Your password
('5ebe2294ecd0e0f08eab7690d2a6ee69  -\n', '')       # <-- Process output

p.communicate() returns an (stdout, stderr) tuple, which is useful for processing the script output.

You may also find this answer useful.

Community
  • 1
  • 1
Adam Matan
  • 128,757
  • 147
  • 397
  • 562