问题描述
我决定回顾一下我的脚本如何提取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
是否有更好,更Python化的方法来完成此任务?我目前不知道有任何其他方式可以做到这一点。
解决方法
到目前为止,除了手动将加密原语应用于消息(不推荐)外,生成子进程是在python中访问gnupg的最佳方法。有一个名为python-gnupg
的第三方模块,但主要是gpg二进制文件的包装。