简体   繁体   中英

Python print redirect as stdin command line argument

I have a binary foo which requires two command line arguments: username and password.

I have written script.py to generate the username and password. Currently, I am using print to print them to stdout and then manually copy and paste them in the shell when I call foo in shell, ie,

$python script.py
username password
(i copied and paste the output below)
$./foo username password

However, I need to generate special bytes which are not printable in stdout and therefore if I copy and paste from stdout, these special byte values are gone. How can I redirect my python output as the argument for foo?

BTW: I have tried using call in subprocess to directly call foo in python, this is not ideal because if I trigger a seg fault in the foo, it does not reflected in bash.

Run:

./foo $(python script.py)

To demonstrates that this works and provides foo with two arguments, let's use this script.py:

$ cat script.py
#!/usr/bin/python
print("name1 pass1")

And let's use this foo so that we can see what arguments were provided to it:

$ cat foo
#!/bin/sh
echo "1=$1 2=$2"

Here is the result of execution:

$ ./foo $(python script.py)
1=name1 2=pass1

As you can see, foo received the name as its first argument and the password as its second argument.

Security Note: The OP has stated that this is not relevant for his application but, for others who may read this with other applications in mind, be aware that passing a password on a command line is not secure: full command lines are readily available to all users on a system.

So subprocess worked but you didn't used because you than didn't got the output from 'foo' (the binary)?

You can use the communicate() function to get output from the binary back.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM