我正在努力让Python pexpect与GNU gpg一起工作。我们没有加载gnupg模块,尝试这样做几乎是不可能的。
我可以通过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
答案 0 :(得分:0)
>
是shell中的重定向。 pexpect
没有运行shell,它运行gpg
可执行文件。请改为使用gpg
选项指定输出文件(--output
)。
以下是使用gpg
模块运行subprocess
的方法:
#!/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)