如何动态计算蛮力方法的大小?例如,如果将所有 IPv6 地址从 0:0:0:0:0:0:0:0 - ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff 打印到文件中,将需要多少次迭代和空间?棘手的部分是线条长度变化的部分。IP 地址只是示例。
想法是您给出给定部分的格式和最大长度。因此,如果变量类型为 '%c' (char),maxlen 为 26,则迭代次数为 26,文本文件中人类格式所需的空间为 26 + 26(一个字符作为分隔符)
def calculate(format, rules):
end = format
for i in rules:
(vartype, maxlen) = rules[i]
end = end.replace(i, vartype % maxlen)
start = format
for i in rules:
(vartype, maxlen) = rules[i]
minlen = 0
start = start.replace(i, vartype % minlen)
start_bytes = len(start)
end_bytes = len(end)
# how to add for example IPv4 calculations
# 0.0.0.0 - 9.9.9.9
# 10.10.10.10 - 99.99.99.99
# 100.100.100.100 - 255.255.255.255
iterations = 0
for i in rules:
if format.find(i) is not -1:
(vartype, maxlen) = rules[i]
if iterations == 0:
iterations = int(maxlen) + 1
else:
iterations *= int(maxlen) + 1
iterations -= 1
needed_space = 0
if start_bytes == end_bytes:
# +1 for separator (space / new line)
needed_space = (1 + start_bytes) * iterations
else:
needed_space = "How to calculate?"
return [iterations, needed_space, start, end, start_bytes, end_bytes]
if __name__ == '__main__':
# IPv4
print calculate(
"%a.%b.%c.%d",
{
'%a': ['%d', 255],
'%b': ['%d', 255],
'%c': ['%d', 255],
'%d': ['%d', 255]
},
)
# IPv4 zero filled version
print calculate(
"%a.%b.%c.%d",
{
'%a': ['%03d', 255],
'%b': ['%03d', 255],
'%c': ['%03d', 255],
'%d': ['%03d', 255]
},
)
# IPv6
print calculate(
"%a:%b:%c:%d:%e:%f:%g:%h",
{
'%a': ['%x', 65535],
'%b': ['%x', 65535],
'%c': ['%x', 65535],
'%d': ['%x', 65535],
'%e': ['%x', 65535],
'%f': ['%x', 65535],
'%g': ['%x', 65535],
'%h': ['%x', 65535]
},
)
# days in year, simulate with day numbers
print calculate(
"ddm%a", #ddmmyy
{
'%a': ['%03d', 365],
},
)
例如:
- 1.2.3.4 占用 7 个字节
- 9.9.9.10 占用 8 个字节
- 1.1.1.100 占用 9 个字节
- 5.7.10.100 占用 10 个字节
- 128.1.1.1 占用 9 个字节
- 等等
示例 0.0.0.0 - 10.10.10.10:
iterations = 0
needed_space = 0
for a in range(0, 11):
for b in range(0, 11):
for c in range(0, 11):
for d in range(0, 11):
line = "%d.%d.%d.%d\n" % (a, b, c, d)
needed_space += len(line)
iterations += 1
print "iterations: %d needed_space: %d bytes" % (iterations, needed_space)
迭代次数:14641 所需空间:122452 字节
进入
print calculate(
"%a.%b.%c.%d",
{
'%a': ['%d', 10],
'%b': ['%d', 10],
'%c': ['%d', 10],
'%d': ['%d', 10]
},
)
结果:[14641, 122452]