根据对问题的评论,为什么不像这样简单地编写一个基于固定长度模板的模糊器:
#! /usr/bin/env python
"""Minimal template based dict string value fuzzer."""
from __future__ import print_function
import random
import string
def random_string(rng, length, chars=string.printable):
"""A random string with given length."""
return ''.join(rng.choice(chars) for _ in range(length))
def dict_string_template_fuzz_gen(rng, dict_in):
"""Given a random number generator rng, and starting from
template dict_in expected to have only strings as values,
this generator function yields derived dicts with random
variations in the string values keeping the length of
those identical."""
while True:
yield dict((k, random_string(rng, len(v))) for k, v in dict_in.items())
def main():
"""Drive a test run of minimal template fuzz."""
k1, k2, k3 = 'ka', 'kb', 'kc'
template = {k1: "aaa", k2: "bbb", k3: "ccc"}
print("# Input(template):")
print(template)
rng = random.SystemRandom()
print("# Output(fuzz):")
for n, fuzz in enumerate(dict_string_template_fuzz_gen(rng,
template), start=0):
print(fuzz)
if n > 3:
break
if __name__ == '__main__':
main()
在用例输入上,它可能会产生以下结果:
# Input(template):
{'kc': 'ccc', 'kb': 'bbb', 'ka': 'aaa'}
# Output(fuzz):
{'kc': '6HZ', 'kb': 'zoD', 'ka': '5>b'}
{'kc': '%<\r', 'kb': 'g>v', 'ka': 'Mo0'}
{'kc': 'Y $', 'kb': '4z.', 'ka': '0".'}
{'kc': '^M.', 'kb': 'QY1', 'ka': 'P0)'}
{'kc': 'FK4', 'kb': 'oZW', 'ka': 'G1q'}
所以这应该给 OP 一些开始,因为它可能是一个引导问题,Python 知识才刚刚开始......
我刚刚破解了它 - 虽然符合 PEP8 - 无论是 Python v2 还是 v3,它都应该可以工作。
许多开放式的工作......但应该让一个人去评估,如果一个库或一些简单的增强编码可能就足够了。只有 OP 会知道,但欢迎对此答案提案发表评论或更新问题。
提示:我几乎总是使用 SystemRandom,因此您可以更稳健地并行化。可能有更快的方法,但在规范中我看不到性能。印刷品当然是散布的,因为这充其量是教育性的。高温高压
更新:阅读了关于仅更改部分字符串以保留一些相似性的 OP 评论后,可以通过以下方式交换上述模糊器功能:
def dict_string_template_fuzz_len_gen(rng, dict_in, f_len=1):
"""Given a random number generator rng, and starting from
template dict_in expected to have only strings as values,
this generator function yields derived dicts with random
variations in the string values keeping the length of
those identical.
Added as hack the f_len parameter that counts the
characters open to be fuzzed from the end of the string."""
r_s = random_string # shorten for line readability below
while True:
yield dict(
(k, v[:f_len + 1] + r_s(rng, f_len)) for k, v in dict_in.items())
然后作为样本输出:
# Input(template):
{'kc': 'ccc', 'kb': 'bbb', 'ka': 'aaa'}
# Output(fuzz):
{'kc': 'cc\t', 'kb': 'bbd', 'ka': 'aa\\'}
{'kc': 'cc&', 'kb': 'bbt', 'ka': 'aa\\'}
{'kc': 'ccg', 'kb': 'bb_', 'ka': 'aaJ'}
{'kc': 'ccc', 'kb': 'bbv', 'ka': 'aau'}
{'kc': 'ccw', 'kb': 'bbs', 'ka': "aa'"}
当调用此函数而不是其他函数时。