美文网首页
关于黑帽子中hexdump函数在python3之后的修改

关于黑帽子中hexdump函数在python3之后的修改

作者: Cichar | 来源:发表于2017-01-06 12:28 被阅读0次

《Python黑帽子:黑客与渗透测试编程之道》书中的TCP代理这一节中hexdump函数是python3之前的写法:

def hexdump(src, length = 16):   
    result = []   
    digits = 4 if isinstance(src, unicode) else 2   
    for i in range(0, len(src), length):
        s = src[i:i+length]
        hexa = b' '.join(['%0*X' % (digits, ord(x)) for x in s])
        text = b''.join([x if 0x20 <= ord(x) < 0x7F else b'.' for x in s])
        result.append( b'%04X  %-*s   %s' % (i, length*(digits + 1), hexa, text))
    print(b'\n'.join(result))

python3之后因为str默认unicode编码,所以:

def hexdump(src, length = 16):
    result = []
    digits = 2 if isinstance(src, str) else 4
    for i in range(0, len(src), length):
        s = src[i:i+length]
        hexa = ' '.join(['%0*X' % (digits, ord(x)) for x in s])
        text = ''.join([x if 0x20 <= ord(x) < 0x7F else '.' for x in s])
        result.append('%04X  %-*s   %s' % (i, length*(digits + 1), hexa, text))
    for i in result:
        print(i)

if __name__ == '__main__':
    hexdump('hello world hello world hello world hello world')

结果为:
0000  68 65 6C 6C 6F 20 77 6F 72 6C 64 20 68 65 6C 6C    hello world hell
0010  6F 20 77 6F 72 6C 64 20 68 65 6C 6C 6F 20 77 6F    o world hello wo
0020  72 6C 64 20 68 65 6C 6C 6F 20 77 6F 72 6C 64       rld hello world

相关文章

网友评论

      本文标题:关于黑帽子中hexdump函数在python3之后的修改

      本文链接:https://www.haomeiwen.com/subject/initbttx.html