【问题标题】:Python pexpect with gpgPython pexpect 与 gpg
【发布时间】:2014-10-14 03:34:24
【问题描述】:

我正在尝试让 Python pexpect 与 GNU gpg 一起工作。我们没有加载 gnupg 模块,尝试这样做几乎是不可能的。

我可以让 pexepct 进行 FTP 和 SSH 工作,但是使用 gpg 我遇到了一个小问题。下面是我从命令行解密文件的命令。我在提示符处输入密码,它运行良好。

# gpg --decrypt encKey_20141009_b7489540_36.00.tar.gpg > encKey_20141009_b7489540_36.00.tar

您需要一个密码来解锁密钥 用户:“XXXXXXXXXXXXXXXXXXXXXXXXXXX” 2048 位 RSA 密钥,ID AD22F55F,创建于 2013-07-18(主密钥 ID 0D56620B)

输入密码:

然而,当我尝试使用 pexpect 时,我遇到了问题。下面是我尝试开始工作的代码:

#!/usr/bin/python

import pexpect
Password = raw_input('Enter passphrase:  ')

child = pexpect.spawn('gpg --decrypt encKey_20141009.tar.gpg > encKey_20141009_.tar')
child.expect('Enter passphrase: ')
child.sendline(Password)

以下是我收到的错误:

Traceback (most recent call last):
  File "./pexepect.py", line 9, in ?
child.expect('Enter passphrase: ')
 File "/usr/lib/python2.4/site-packages/pexpect.py", line 1311, in expect
return self.expect_list(compiled_pattern_list, timeout, searchwindowsize)
File "/usr/lib/python2.4/site-packages/pexpect.py", line 1325, in expect_list
  return self.expect_loop(searcher_re(pattern_list), timeout, searchwindowsize)
File "/usr/lib/python2.4/site-packages/pexpect.py", line 1396, in expect_loop
raise EOF (str(e) + '\n' + str(self))
pexpect.EOF: End Of File (EOF) in read_nonblocking(). Exception style platform.
<pexpect.spawn object at 0x2b2dfe13f350>
version: 2.3 ($Revision: 399 $)
command: /usr/bin/gpg
args: ['/usr/bin/gpg', '--decrypt', 'encKey_20141009.tar.gpg', '>', 'encKey_20141009.tar']
searcher: searcher_re:
    0: re.compile("Enter passphrase: ")
buffer (last 100 chars):
before (last 100 chars): usage: gpg [options] --decrypt [filename]

after: pexpect.EOF
match: None
match_index: None
exitstatus: 2
flag_eof: True
pid: 14399
child_fd: 3
closed: False
timeout: 30
delimiter: pexpect.EOF
logfile: None
logfile_read: None
logfile_send: None
maxread: 2000
ignorecase: False
searchwindowsize: None
delaybeforesend: 0.05
delayafterclose: 0.1
delayafterterminate: 0.1

【问题讨论】:

    标签: python pexpect gnupg


    【解决方案1】:

    &gt; 是 shell 中的重定向。 pexpect 不运行 shell,它运行 gpg 可执行文件。使用 gpg 选项指定输出文件 (--output)。

    以下是使用subprocess 模块运行gpg 的方法:

    #!/usr/bin/env python3
    import os
    from subprocess import Popen
    
    passphrase = input('Enter passphrase: ')
    file_to_decrypt = 'encKey_20141009.tar.gpg'
    in_fd, out_fd = os.pipe()
    cmd = ['gpg', '--passphrase-fd', str(in_fd)]
    cmd += ['--output', os.path.splitext(file_to_decrypt)[0]]
    cmd += ['--decrypt', file_to_decrypt]
    with Popen(cmd, pass_fds=[in_fd]):
        os.close(in_fd) # unused in the parent
        with open(out_fd, 'w') as out_file:
            out_file.write(passphrase)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多