python - 在 Python 子进程上使用小于号 (<)

标签 python subprocess popen

直接在控制台上我可以使用 openssl 加密和解密字符串。由于 openssl 需要一个输入文件,我可以告诉它使用小于号 (<) 从我输入的 echo 中获取此文件,如下所示:

加密:

# openssl enc -aes-256-cbc -in <(echo "helloworld") -a -k 12345678 -S 12345678 -iv 12345678
U2FsdGVkX18SNFZ4AAAAAKJTAirWf4KnDHYXlIF/87Y=

解密:

# openssl enc -aes-256-cbc -in <(echo "U2FsdGVkX18SNFZ4AAAAAKJTAirWf4KnDHYXlIF/87Y=") -d -a -k 12345678 -S 12345678 -iv 12345678
helloworld

使用Python,我需要解密字符串“U2FsdGVkX18SNFZ4AAAAAKJTAirWf4KnDHYXlIF/87Y=”并打印出“helloworld”。

到目前为止,我已经尝试过此操作,但总是出现错误:

from subprocess import Popen, PIPE
cmd = 'openssl enc -aes-256-cbc -in < (echo U2FsdGVkX18SNFZ4AAAAAKJTAirWf4KnDHYXlIF/87Y=) ' \
      '-d -a -k 12345678 -S 12345678 -iv 12345678'
x = Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output = x.communicate()[0]
print output

我得到的错误是:/bin/sh: 1: 语法错误:“(”意外

有办法实现我的需求吗?

最佳答案

$ openssl enc --help
...
 -in file           Input file to read from (default stdin)

该命令默认从stdin读取,如果您希望openssl从文件读取,则只需要-in参数而不是管道。也就是说,默认情况下这也可以:

echo helloworld | openssl enc ...
# (no -in!)

与此等效的 Python 是:

x = Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output = x.communicate(input='helloworld')[0]

(再次强调,cmd 中没有 -in,让 opensslstdin 读取。)

关于python - 在 Python 子进程上使用小于号 (<),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48503452/

相关文章:

python - 如何分块具有特定大小和条件的大文件

python - subprocess.check_output 忽略 euid

python - 杀死进程不杀死子进程并且不关闭终端窗口

python - 从列表列表中删除整个列表

python - 需要一个 defaultdict,其值为两个列表

python - Linux 中的主动文件夹观察程序

c++ - 从 popen 到 ifstream.open 的文件输出列表

Python 子进程仅在 cron 中返回非零退出状态

python - 使用主 Python 脚本中的子进程并行执行 2 个独立的 Python 脚本

python - Popen 包含需要对所有输出说是的命令