gpg --passphrase-fd not working with python 3 subprocess

拈花ヽ惹草 提交于 2019-11-29 05:20:09

close_fds=True on POSIX systems on Python 3. Use pass_fds to pass input pipe file descriptor:

#!/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)

You could also pass the passphrase via stdin:

#!/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'))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!