-
Notifications
You must be signed in to change notification settings - Fork 1
/
tcpdump_tunes.py
executable file
·90 lines (66 loc) · 2.63 KB
/
tcpdump_tunes.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
83
84
85
86
87
88
89
90
#!/usr/bin/env python
# Parses the text output of tcpdump (with no -v) from stdin, makes music
import argparse
import re
import sys
from datetime import datetime
import midi
MIN_SPACING = 30
MIN_LENGTH = 20
def main():
line_re = r"(?P<timestamp>\d{2}:\d{2}:\d{2}.\d{6}) IP (?P<src>\d+\.\d+\.\d+\.\d+)\.(?P<sport>\d+) > (?P<dst>\d+\.\d+\.\d+\.\d+)\.(?P<dport>\d+): (?:Flags \[(?P<flags>[SFPRUWE\.]+)\])?.+?length (?P<length>\d+)"
arg_parser = argparse.ArgumentParser(description="MIDI from tcpdump")
arg_parser.add_argument('-f',
help="Output file, omit or give - for stdout",
metavar='file',
default='-')
args = arg_parser.parse_args()
if args.f == '-':
output_file = sys.stdout
else:
output_file = open(args.f, 'w')
pattern = midi.Pattern()
track = midi.Track()
pattern.append(track)
last_time = datetime.now()
line = sys.stdin.readline()
while line:
match = re.match(line_re, line)
if match:
data = match.groupdict()
# Get the difference between now and the last event
now = datetime.strptime(data['timestamp'], '%H:%M:%S.%f')
spacing = int((now - last_time).microseconds / 1000.0)
last_time = now
if spacing < MIN_SPACING:
spacing = MIN_SPACING
# Determine note length based on packet length
pkt_length = int(data.get('length', 0))
note_length = int(pow(pkt_length, 0.75))
if note_length < MIN_LENGTH:
note_length = MIN_LENGTH
# determine the note to play based on TCP flags
note = midi.C_0
flags = data.get('flags', '')
if flags:
if 'S' in flags:
note = midi.D_0
elif '.' in flags:
note = midi.C_0
elif 'F' in flags:
note = midi.F_0
elif 'R' in flags:
note = midi.G_0
# Determine the octave based on the src and dst IPs
octave = hash((data['src'], data['dst'])) % 6 + 2
note = note + octave * 12
# Finally, append the note to the track
track.append(midi.NoteOnEvent(tick=spacing, velocity=70, pitch=note))
track.append(midi.NoteOffEvent(tick=note_length, pitch=note))
line = sys.stdin.readline()
# Dump MIDI track to stdout
track.append(midi.EndOfTrackEvent(tick=1))
midi.write_midifile(output_file, pattern)
return 0
if __name__ == '__main__':
exit(main())