How to use Python with wireshark.

This example code demonstrates how to use Python with wireshark to create a IP monitor script. For this we combine Python with tshark the command line of wireshark.

IP Packet Monitor script description

The IP packer monitor captures all IP packets which are targeted to a system for a specific duration. The source IP address of theses packets are written to an output file. The name of the script is ippacketmonitor.py. The screenshot of the code on Ubuntu is shown below.


The code line numbers and appropriate explanation is provided below.

Join our Course to Build Network Automation tools and scripts with Python and Scapy on Udemy

Create a file named ippacketmonitor.py.

1.Imports the OS module
2.Captures tshark on the eth0 interface (sudo tshark –i eth0) with a read filter applied to capture IP packets with destination address in the header as 192.168.1.25(-R ip.dst=’=192.168.1.25’), retrieves the source IP address in the packets (-T fields –e ip.src) , for 30 second duration (-a duration:30), and writes the source IP address values to the output.txt file (output.txt)
3.Opens the command using the appropriate function
4.Opens the output.txt file, in which the IP addresses are written.
5.Initializes a count variable as 0.
6.Starts a for loop for reading the lines in the file.
7.Strip each lines
8.Increments the count variable with 1 , for every lines stripped.
9.Prints the number of IP addresses which sent packets to the Ubuntu system which is the count variable.
10. Prints the appropriate message to view the output.txt file.

The tool is executed using the command sudo python ippacketmonitor.py from the system command line. The screenshot of the output is shown below.

Join our Course to Build Network Automation tools and scripts with Python and Scapy on Udemy