Python

How to Capture Packets Using Python

In general, we use the Wireshark tool to capture the network packets. But this is a manual process. In some situation, we may need to capture the networking frames using the Python script in Linux. In this article, we will learn how to use the Python script to capture the frames in either Ethernet or WLAN interface.

How to Make the Linux Setup Ready

There are some prerequisites to run a Python script to capture the live frames in Linux.

1. Install Python 3.7

We need Python 3.7 to run the live capture script. For example: Ubuntu 18.04/20.04 does not have Python 3.7 by default. So, we need to install it using the following steps:

$ sudo apt update

$ sudo apt install python3.7

If this does not work, we need to check on the internet to solve the issue or use the following commands:

$ wget https://www.python.org/ftp/python/3.7.4/Python-3.7.4.tgz

 

$ tar -xf Python-3.7.4.tgz

$ cd Python-3.7.4

$ ./configure --enable-optimizations

$ sudo make

$ sudo make install

2. Install the PyShark Module for Python 3.7

To do the live capture using Python, we need to install the PyShark module for Python 3.7. Otherwise, we get the following error:

Traceback (most recent call last):

File "capture.py", line 1, in <module>

import

ImportError: No module named 'pyshark'

Here is the step to install PyShark:

$ python3.7 -m pip install pyshark

In case we get any pip upgrade message, we can update pip3 using the following command:

$ sudo pip3 install --upgrade pip

3. Install TShark

Install tshark using the following command:

$ sudo apt install tshark

Python Script to Capture Live Packets

Here is the Python script to do live capturing on the provided interface:

import pyshark

import os

#********USER ACTION REQUIRED*********#

# Please change interfaceId/name for below line as per your system.

INTERFACE_NAME="wlp2s0"

capture_size = 0

def capture_packet(time):

file = "capture.pcapng"

output = open(file, "w")

capture = pyshark.LiveCapture(interface=INTERFACE_NAME, output_file=file)

capture.set_debug()

capture.sniff(timeout=time)

output.close()

return os.path.getsize(file)

#Step1 -> Entry to code

print("****Hope you have added correct interface name into this python file****\n")

time = int(input("How long(sec) to capture traffic? [Value should be more than 20 sec]\n"))

if time < 20:

print("Timeout must be over 20 seconds.\n")

else:

print("\nCapture time is: ", time, "sec for each interface.\n\n ....Please wait....")

#Step2 -> Functions

capture_size = capture_packet(time+10) #2. Start capturing packets on provided interface

if capture_size >= 1073741824:

print("|---Total Packet size captured is => ",'{0:.2f}'.format(capture_size/(1024*1024*1024)), "GB ---|")

elif capture_size >= 1048576:

print("|---Total Packet size captured is => ",'{0:.2f}'.format(capture_size/(1024*1024)), "MB ---|")

elif capture_size >= 1024:

print("|---Total Packet size captured is => ",'{0:.2f}'.format(capture_size/1024), "KB ---|")

else:

print("|---Total Packet size captured is => ",capture_size, "bytes ---|")

Here, we are capturing live using the following line in the script:

capture = pyshark.LiveCapture(interface=INTERFACE_NAME, output_file=file)

Input for Python Script:

1) We need to input the interface name in the following line:

INTERFACE_NAME="wlp2s0"

2) After we run the script using the following command, the user will ask to provide how long does the user wants to do the live capture.

$ sudo python3.7 capture_using_python.py

Here, the input is required in seconds greater than 20.

Output for Python Script:

Once the Python script is executed:

1) A capture file is given as output in the same directory where the Python script is present. If we open this capture file, we will see the networking frames. Let us run the script and see.

2) The size of the output capture file is shown in the terminal.

Run the Script:

$ sudo python3.7 capture_using_python.py

****Hope you have added correct interface name into this python file****

How long(sec) to capture traffic? [Value should be more than 20 sec]

30

Capture time is: 30 sec for each interface.

....Please wait....

Output:

2023-05-09 01:34:28,004 - LiveCapture - DEBUG - Creating Dumpcap subprocess with parameters: /usr/bin/dumpcap -q -i wlp2s0 -w -

2023-05-09 01:34:28,023 - LiveCapture - DEBUG - Dumpcap subprocess (pid 2902) created

2023-05-09 01:34:29,517 - LiveCapture - DEBUG - Creating TShark subprocess with parameters: /usr/bin/tshark -l -n -T pdml -w capture .pcapng -i -

2023-05-09 01:34:29,519 - LiveCapture - DEBUG - Executable: /usr/bin/tshark

2023-05-09 01:34:29,537 - LiveCapture - DEBUG - Capturing on 'wlp2s0'

2023-05-09 01:34:29,539 - LiveCapture - DEBUG - File: -

2023-05-09 01:34:29,543 - LiveCapture - DEBUG - TShark subprocess (pid 2916) created

2023-05-09 01:34:29,544 - LiveCapture - DEBUG - Starting to go through packets

2023-05-09 01:34:29,641 - LiveCapture - DEBUG - Running as user "root" and group "root". This could be dangerous.

2023-05-09 01:34:30,989 - LiveCapture - DEBUG - Capturing on 'Standard input'

2023-05-09 01:35:06,793 - LiveCapture - DEBUG - Cleanup Subprocess (pid 2902)

2023-05-09 01:35:06,852 - LiveCapture - DEBUG - Cleanup Subprocess (pid 2916)

|---Total Packet size captured is => 3.05 KB ---|

Conclusion

From this article, we learned how to capture the live networking packets in Linux using the Python script. This helps us to solve many manual jobs. Also, we can explore many other options from the PyShark package and modify the script as per our needs.

About the author

Bamdeb Ghosh

Bamdeb Ghosh is having hands-on experience in Wireless networking domain.He's an expert in Wireshark capture analysis on Wireless or Wired Networking along with knowledge of Android, Bluetooth, Linux commands and python. Follow his site: wifisharks.com