-
Notifications
You must be signed in to change notification settings - Fork 9
/
utils.py
82 lines (69 loc) · 2.13 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#!/usr/bin/env python
"""
Utility methods.
Copyleft 2011 Ian Gallagher <[email protected]>
Some methods taken directly, or with modification from the Scapy project
(http://www.secdev.org/projects/scapy) - noted accordingly
"""
from textwrap import TextWrapper
from terminal import TerminalController
def color_string(data, color):
# Setup a TerminalController for formatted output
term = TerminalController()
result = term.render("${" + color.upper() + "}" + data + "${NORMAL}")
return(result)
def sane(x):
"""
From Scapy's utils.py
"""
r=""
for i in x:
j = ord(i)
if (j < 32) or (j >= 127):
r=r+"."
else:
r=r+i
return ' '.join((r[:8], r[8:])).strip()
def indent(data, spaces):
return '\n'.join(map(lambda x: ' ' * spaces + x, data.split('\n')))
def hexdump(x, indent=False):
"""
From Scapy's utils.py, modified to return a string instead of print directly,
and just use sane() instead of sane_color()
"""
result = ""
x=str(x)
l = len(x)
i = 0
while i < l:
result += "%08x " % i
for j in range(16):
if i+j < l:
result += "%02x " % ord(x[i+j])
else:
result += " "
if j%16 == 7:
result += " "
result += " "
result += sane(x[i:i+16]) + "\n"
i += 16
if indent:
"""
Print hexdump indented 4 spaces, and blue - same as Wireshark
"""
indent_count = 4 # Same as Wireshark's hex display for following TCP streams
tw = TextWrapper(width = 78 + indent_count, initial_indent = ' ' * indent_count, subsequent_indent = ' ' * indent_count)
result = tw.fill(result)
result = color_string(result, "CYAN")
return(result)
else:
"""
Print hexdump left aligned, and red - same as Wireshark
"""
result = color_string(result.strip(), "RED")
return(result)
if __name__ == "__main__":
import os
print(hexdump('\xff'*68))
print(hexdump('\x41'*61, indent=True))
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4