python - 如何在没有子进程的情况下导入和使用系统 gpg 密钥
问题描述
我决定回顾一下我的脚本如何提取 gpg 密钥并使用该密钥加密密码。目前,我正在使用子进程在主机上运行命令,如下所示:
def check_for_imported_gpg_key():
gpg_keys = subprocess.check_output(["gpg", "-k"]).decode("utf-8")
if "pillar" in gpg_keys:
return True
else:
return False
def encrypt_pillar_password(password):
hashed_pass = crypt.crypt(str(password))
key_imported = check_for_imported_gpg_key()
if key_imported is False:
print("OI! Import the key bud!")
print("Encrypting Password with Pub Key")
process = subprocess.Popen(
(
"gpg",
"--armor",
"--batch",
"--trust-model",
"always",
"--encrypt",
"-r",
"pillar",
),
stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
stderr=subprocess.PIPE,
)
gpg_message = process.communicate(input=hashed_pass.encode())[0]
if "BEGIN PGP MESSAGE" in str(gpg_message):
return gpg_message
else:
print("Something went wrong when generating the encrypted hash")
print(str(gpg_message))
return None
有没有更好、更 Pythonic 的方式来完成这项任务?我目前不知道有任何其他方法可以做到这一点。
解决方案
到目前为止,除了手动将加密原语应用于消息(不推荐)之外,生成子进程是在 python 中访问 gnupg 的最佳方式。有一个名为 的第三方模块python-gnupg
,但它主要是 gpg 二进制文件的包装器。
推荐阅读
- language-server-protocol - 如何手动请求 clangd 或实现 ClangdServer 以完成代码
- java - 我的菜单栏不在我的窗口顶部?
- reactjs - React Native 不显示图像
- python - 将 datetime.now() 添加到 print_exc
- arrays - 如何正确编写返回给定数组的方法
- python - 无法使用 python api 修改 MT5 中的止损
- android - Android Kotlin - 将 HTML 字符串拆分为保持 HTML 标签的块
- mysql - 如何使用 MySQL 过滤所需的行
- google-apps-script - Google 应用程序脚本变量声明灰显
- javascript - FancyTree 区分拖动到节点和节点下