=================================================================================================
stream_ts.py
=================================================================================================
import sys
from subprocess import Popen, PIPE

"""
Script to find start and end time of established tcp sessions.

Usage: python stream_ts.py <pcap file> [tshark-filter]

Exmples of option parameter <tshark-filter>: tcp.port==4444
"""

def three_hand_shake(l):
	"""
	Check whether there is a three-way handshake in the packets in l
	Returns the index into the list if found, otherwise returns None
	"""

	# tcp.flags is sixth element in packet
	for i in range(len(l)-2):
		if l[i][6] == "0x02" and l[i+1][6] == "0x12" and l[i+2][6] == "0x10":
			return i
	return None

def fm_ts(ts):
	"""
	Format timestamp ts, including the rounded value to a tenth of a second.
	"""
	f= float(ts)
	return "%.1f (%s)" % (f, ts)

# main

# Get commandline arguments
if len(sys.argv) < 2 or len(sys.argv) > 3:
	print "Usage: python %s <pcap file> [tshark-filter]" % sys.argv[0]
	sys.exit()

if len(sys.argv) == 3:
	# We always only want to see tcp packets
	tshark_filter = "tcp and %s" % sys.argv[2]
else:
	tshark_filter = "tcp"

# Execute tshark command
tshark_output = Popen("tshark -r %s -T fields -e frame.time -e frame.time_relative -e tcp.stream -e ip.src -e tcp.srcport -e ip.dst -e tcp.dstport -e tcp.flags %s -E separator=';'" % (sys.argv[1], tshark_filter), shell=True, stdout=PIPE).communicate()[0]

packets={}
for line in tshark_output.splitlines():
	try:
		ts, ts_rel, stream, src, srcport, dst, dstport, tcp_flags = line.split(';')
		if not packets.has_key(stream):
			packets[stream]=[]
		packets[stream].append((ts, ts_rel, src, srcport, dst, dstport, tcp_flags))
	except ValueError:
		print "Invalid input"
		sys.exit(-1)

for stream in packets.keys():
	handshake = three_hand_shake(packets[stream])
	if handshake != None:
		print "="*60
		p=packets[stream][handshake]
		print "Connection: %s:%s -> %s:%s" % (p[2], p[3], p[4], p[5])
		print "Connection established at: %s. Relative timestamp: %s" %(p[0],fm_ts(p[1]))
		print "Connection closed at: %s. Relative timestamp: %s" % (packets[stream][-1][0], fm_ts(packets[stream][-1][1]))
		print "="*60

