Otto background

Visualizing Network Data Using Python: Part 1

If you are in IT or Security you have had to look at packets to troubleshoot or investigate an issue. Tools like Wireshark are great, but sometimes you need to automate or want to run something all on the terminal. This is a three-part post on visualizing network data with Python. We’ll read a packet capture and graph the number of times each source IP is seen in the packet.

Reading PCAP data with Python

Before we start visualizing the data we will learn how to read PCAP data with Python using ScaPy.  For this example we will use 2 external modules and 1 built in module. ScaPy is a great tool for manipulating and reading packets and PrettyTables is just what you would imagine it is, a library to print pretty tables.

Installation
pip3 install scapy-python3
pip3 install prettytable

Imports
from scapy.all import *
from collections import Counter
from prettytable import PrettyTable

First we will tell ScaPy to read all of the packets in the PCAP to a list, to do that use the rdpcap function.
packets = rdpcap('example.pcap')

Packets in ScaPy have elements, we will only be dealing with packet’s IP data.  Each packet has attributes like source IP, destination IP, source port, destination port, bytes, etc.  To print a source IP use pkt[IP].src
print(pkt[IP].src)

For our example we will need to read a PCAP file and store the source IP in a list. To do that we will loop through the packets using a try/except as not every packet will have the information we want (malformed, retransmit, etc).
srcIP=[]
for pkt in packets:
if IP in pkt:
try:
           srcIP.append(pkt[IP].src)
except:
pass

Now that you have a list of IPs from the packets we will use a counter to create a count.
cnt=Counter()

for ip in srcIP:
cnt[ip] += 1

Now we can use PrettyTable to sort and print the data. The first step is to create the table with table().

table= PrettyTable(["IP", "Count"])

Next we will loop through the data and add them to the table  from highest to lowest .
for ip, count in cnt.most_common():
   table.add_row([ip, count])

And lastly we print the column.
print(table)

The whole script beginning to end looks like:


To run it, create a PCAP with tcdpump:
sudo tcpdump -w example.pcap -c10000

Now run the program and see results.

Check back next week when we introduce using graphing packages to create graphs of network data using Python!


Automox for Easy IT Operations

Automox is the cloud-native IT operations platform for modern organizations. It makes it easy to keep every endpoint automatically configured, patched, and secured – anywhere in the world. With the push of a button, IT admins can fix critical vulnerabilities faster, slash cost and complexity, and win back hours in their day. 

Grab your free trial of Automox and join thousands of companies transforming IT operations into a strategic business driver.

Dive deeper into this topic

loading...