【问题标题】:gpg --passphrase-fd not working with python 3 subprocessgpg --passphrase-fd 不适用于 python 3 子进程
【发布时间】:2013-12-01 13:38:59
【问题描述】:

以下脚本encrypt_me.py (modified from another post) 使用 gpg 对自身进行加密,并以装甲形式打印出密文。

但是它只适用于 python2.7 而不是 python3?你知道它在 python3 上运行时出了什么问题吗?

import subprocess
import shlex
import os
import sys

in_fd, out_fd = os.pipe()
passphrase = 'passsssphrase'
os.write(out_fd, passphrase.encode('utf-8'))
os.close(out_fd)
cmd = 'gpg --passphrase-fd {fd} -c --armor'.format(fd=in_fd)

with open(__file__,'r') as stdin_fh:
    proc=subprocess.Popen(shlex.split(cmd),
                          stdin=stdin_fh,
                          stdout=sys.stdout)
    proc.communicate()

os.close(in_fd)

用python2.7:

$ python encrypt_me.py
Reading passphrase from file descriptor 3    
-----BEGIN PGP MESSAGE-----
Version: GnuPG v1.4.12 (GNU/Linux)

jA0EAwMCXrbnOPX+CipgycBD3ErAKmba6UvtA35mjomOlbiOHX2M0bULbV+v8q8U
AJ+sTQcFZK+NoauMgUFm39/ZcNoI7W5u78x8dj5B1N6jLk11C7MgmkNmT5CiliQO
kl/el0fDAMnksrqGFpUC6+4ECOTJPpj0Z/Cn/3/62kLHkkbAxs+wyS8lGxXEIEKH
XFl3OLRlVmCbvtwzrNMFLiD/St6NHu3Wh9S2xt8fe0PAEAZoYlWWx8lnEQEKewq9
EzLlkLldZaDNja3ePzWZ8Z6AeDtowBa8kj+8x/HjxfKLGheBBNQuaeBdcSHgE/OW
esS/tEesQUlfUgqrZc2uBalLTV9xwyIpcV4cg8BubPWFCcBrDQ==
=iziW
-----END PGP MESSAGE-----

使用python3:

$ python3 encrypt_me.py
Reading passphrase from file descriptor 3 ...

gpg: error creating passphrase: invalid passphrase
gpg: symmetric encryption of `[stdin]' failed: invalid passphrase

【问题讨论】:

    标签: python subprocess gnupg


    【解决方案1】:

    close_fds=True 在 Python 3 上的 POSIX 系统上。使用 pass_fds 传递输入管道文件描述符:

    #!/usr/bin/env python3
    import os
    import shlex
    import sys
    from subprocess import Popen
    
    
    passphrase = 'passsssphrase'
    file_to_encrypt = sys.argv[1] if len(sys.argv) > 1 else 'encrypt_me.py'
    
    in_fd, out_fd = os.pipe()
    cmd = 'gpg --passphrase-fd {fd} -c --armor -o -'.format(fd=in_fd)
    with Popen(shlex.split(cmd) + [file_to_encrypt], pass_fds=[in_fd]):
        os.close(in_fd) # unused in the parent
        with open(out_fd, 'w', encoding='utf-8') as out_file:
            out_file.write(passphrase)
    

    您也可以通过标准输入传递密码:

    #!/usr/bin/env python3
    import sys
    from subprocess import PIPE, Popen
    
    
    passphrase = 'passsssphrase'
    file_to_encrypt = sys.argv[1] if len(sys.argv) > 1 else __file__
    
    cmd = 'gpg --passphrase-fd 0 -c --armor -o -'.split()
    with Popen(cmd + [file_to_encrypt], stdin=PIPE) as process:
        process.stdin.write(passphrase.encode('utf-8'))
    

    【讨论】:

    • 我看到了,close_fs默认值从False变成了True,pass_fds是指定通过哪个fd而不被关闭。
    猜你喜欢
    • 2018-09-01
    • 1970-01-01
    • 2018-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-17
    • 2018-03-09
    • 1970-01-01
    相关资源
    最近更新 更多