1
import os

dictionaryfile = "/root/john.txt"
pgpencryptedfile = "helloworld.txt.gpg"

array = open(dictionaryfile).readlines()


for x in array:
    x = x.rstrip('\n')
    newstring = "echo " + x + " | gpg --passphrase-fd 0 " + pgpencryptedfile
    os.popen(newstring)

我需要在 for 循环中创建一些东西来读取 gpg 的输出。当 gpg 输出这个字符串gpg: WARNING: message was not integrity protected时,我需要关闭循环并打印成功!

我该怎么做,背后的原因是什么?

感谢大家!

4

3 回答 3

1

使用subprocess.check_outputgpg根据其输出调用和中断循环。

像这样的东西(未经测试,因为我什么都不知道gpg):

import subprocess

dictionaryfile = "/root/john.txt"
pgpencryptedfile = "helloworld.txt.gpg"

with open(dictionaryfile, 'r') as f:
    for line in f:
        x = line.rstrip('\n')
        cmd = ["echo " + x + " | gpg --passphrase-fd 0 " + pgpencryptedfile]
        output = subprocess.check_output(cmd, shell=True)
        if 'gpg: WARNING: message was not integrity protected' in output:
            break
于 2012-10-10T03:10:42.113 回答
1
import subprocess


def check_file(dictfile, pgpfile):
    # Command to run, constructed as a list to prevent shell-escaping accidents
    cmd = ["gpg", "--passphrase-fd", "0", pgpfile]

    # Launch process, with stdin/stdout wired up to `p.stdout` and `p.stdin`
    p = subprocess.Popen(cmd, stdin = subprocess.PIPE, stdout = subprocess.PIPE)

    # Read dictfile, and send contents to stdin
    passphrase = open(dictfile).read()
    p.stdin.write(passphrase)

    # Read stdout and check for message
    stdout, stderr = p.communicate()
    for line in stdout.splitlines():
        if line.strip() == "gpg: WARNING: message was not integrity protected":
            # Relevant line was found
            return True

    # Line not found
    return False

然后使用:

not_integrity_protected = check_file("/root/john.txt", "helloworld.txt.gpg")
if not_integrity_protected:
    print "Success!"

如果“gpg: WARNING:”消息实际上是打开的stderr(我怀疑是这样),请将subprocess.Popen行更改为:

p = subprocess.Popen(cmd, stdin = subprocess.PIPE, stderr = subprocess.PIPE)

..和 for 循环 from stdoutto stderr,像这样:

for line in stderr.splitlines():
于 2012-10-10T03:31:16.177 回答
0

您可以使用允许您使用的子流程模块:

subprocess.call(args, *, stdin, stdout, stderr, shell)

(有关如何使用参数,请参阅Python 文档。)

这很好,因为您可以轻松读取您调用的任何程序的退出代码。

例如,如果您将“newstring”更改为:

"echo " + x + " | gpg --passphrase-fd 0 " + pgpencryptedfile | grep 'gpg: WARNING: message was not integrity protected'

如果有匹配项,grep 将返回 0,如果没有找到匹配项,则返回 1。(来源

grep 的退出代码将从 subprocess.call() 函数返回,您可以轻松地将其存储在变量中并使用 if 语句。

编辑:正如 Matthew Adams 在下面提到的,您还可以阅读 gpg 本身的退出代码。

于 2012-10-10T03:10:53.030 回答