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 packetsniffer.py
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.
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.