Python 使用密码解码后从字符串中获取变量

Python get variables from string after decoding with cryptography

我正在使用登录信息对文件进行解密。 当我解密它时,我最终得到一个字符串中的信息。 这是一段代码:

decrypted_message = encryption_type.decrypt(original)
testing = decrypted_message.decode("utf-8")
print("test: ", testing)

输出为:

test:  ip = "192.168.xxx.xxx", username = "xxx", password = "xxx"

如何从这个字符串中获取 ip、用户名和密码?

如果某个方法需要更改输出,我仍然可以更改输出。 我也使用解码器,否则我会在输出前得到 b'(我知道是字节,但我不知道如何使用)。

如果您的字符串如您问题中所示:

s = 'ip = "192.168.xxx.xxx", username = "xxx", password = "xxx"'
print(s.split()[2][1:-2])

如果你的输出真的是一个字符串,像这样的东西会解析它:

a = 'ip = "192.168.xxx.xxx", username = "xxx", password = "xxx"'
parsed = dict(x.replace('"', "").split(" = ") for x in a.split(", "))
# {'ip': '192.168.xxx.xxx', 'username': 'xxx', 'password': 'xxx'}

但正如评论中所述,您 最好首先将数据存储在 json 中:

import json
s = json.dumps(dict(ip="192.168.1.1", username="me", pass="xx"))
encode(s) # dummy fn
decoded = json.loads(decode(s))
# decoded is a dict

所以我把加密前的明文改成了json:

{"ip": "192.168.xx.xx", "username": "xx", "password": "xx"}

现在它是 json,我能够在解析后打印变量。

settings = json.loads(testing)
print(settings["ip"])

现在我的项目有了解决方案。