gpt4 book ai didi

python - 列表到字典,但每个键有多个值

转载 作者:行者123 更新时间:2023-12-01 05:02:09 24 4
gpt4 key购买 nike

我正在收集以下数据文件名、用户名和密码。这些数据是通过遍历每个目录寻找带有明文凭据的文档(主要是脚本)来收集的。这个想法是收集系统管理员所遵循的不良做法的证据。

我的脚本做得足够好,但是我试图了解处理数据的最佳方法。我想将该特定文件中找到的文件名和凭据放入字典中。因此,键是文件名,值是在该文件中找到的凭据。

我已经弄清楚了如何将数据添加到字典中,但我不完全确定如何也无法找到一种方法将 2 个列表放入字典中,并且字典为 1 个键托管多个值。任何指示将不胜感激。正如评论所建议的,当前未使用带有 #if not m: add nonmatched data to un_matched list 的行。我想将不匹配的数据添加到另一个列表(用于调试)

代码

dirt = "~/Desktop/tmp"

def get_files():
regs = ["(.*)((U|u)ser(.*))(\s=\s\W\w+\W)", "(.*)((U|u)ser(.*))(\s=\s\w+)", "(.*)((P|p)ass(.*))\s=\s(\W(.*)\W)", "(.*)((P|p)ass(.*))(\s=\s\W\w+\W)"]
combined = "(" + ")|(".join(regs) + ")"
cred_results = []
creds = []
un_matched = []
filesfound = []
for root, dirs, files in os.walk(dirt):
for filename in files:
if filename.endswith(('.bat', '.vbs', '.ps', '.txt')):
readfile = open(os.path.join(root, filename), "r")
for line in readfile:
m = re.match(combined, line)
if m:
creds.append(m.group(0))
#if not m: add non matched data to un_matched list
filesfound.append(os.path.join(root, filename))
cred_results = [line.rstrip() for line in creds]

print cred_results
print filesfound

脚本的当前输出

['strUser = "guytom"', 'strPassword = "P@ssw0rd1"', 'strUsername = "guytom2"', 'strPass = "SECRETPASSWORD"']
['~/Desktop/tmp/Domain/Policies/{31B2F340-016D-11D2-945F-00C04FB984F9}/USER/Scripts/Logon/logonscript1.vbs', '~/Desktop/tmp/Domain/Policies/{31B2F340-016D-11D2-945F-00C04FB984F9}/USER/Scripts/Logon/logonscript2.bat']

最佳答案

您可以将字典与 dict.setdefault 一起使用:

    d = {} # create dict 
for root, dirs, files in os.walk(dirt):
for filename in files:
if filename.endswith(('.bat', '.vbs', '.ps', '.txt')):
readfile = open(os.path.join(root, filename), "r")
d.setdefault(filename,[]) # set default value to a list
for line in readfile:
m = re.match(combined, line)
if m:
creds.append(m.group(0))
d[filename].append(m.group(0).rstrip()) # append data to the key's list stripping newlines etc..

如果您想跟踪不匹配的数据,只需添加第二个字典并使用 with 即可自动关闭您的文件:

    for root, dirs, files in os.walk(dirt):
for filename in files:
if filename.endswith(('.bat', '.vbs', '.ps', '.txt')):
with open(os.path.join(root, filename), "r") as readfile:
matched_d.setdefault(filename,[])
unmatched_d.setdefault(filename,[])
for line in readfile:
m = re.match(combined, line)
if m:
creds.append(m.group(0))
d[filename].append(m.group(0).rstrip())
else:
unmatched_d[filename].append(add_data_here)

关于python - 列表到字典,但每个键有多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25838237/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com