Python Packet Sniffer

In this tutorial, we explain how to write a Python packet sniffer. For this , we combine the command line version of wireshark, which is tshark for sniffing. Scapy can also be used in lieu of tshark for this purpose.

A sample code with explanation is provided below.

1. The first step is to to create a Python file with any name. We shall call it
2. The second step is to import the OS module. This is used for calling the appropriate tshark command from the code.
3. The 3rd step is to call the tshark code with the required filter. For ex, if it is required to sniff for TCP packets on the network for 60 seconds to an output file, the code b=’sudo tshark -i eth0 -R “tcp” -a duration:60>output.txt’ is used.
4. The 4th step is to call the command from python using the popen, which is a system command.

The detailed code is shown below.

import os
print “Monitoring broadcast packets on the network for 1 minute”
b=’sudo tshark -i eth0 -R “tcp” -a duration:60>output.txt’

The above script would run for 60 seconds and will sniff all tcp packets and write it to the output.txt file, which can be used for analysis.

Become a packet crafting expert with our video course – Python Network programming

Building Network monitoring tools with Python and Tshark