In the world of networking, analyzing network traffic is a fundamental skill. Whether you’re troubleshooting, monitoring, or learning, tools like Pyshark provide a programmatic way to capture and examine network packets, both on local machines and servers. Pyshark, a Python wrapper for Wireshark’s TShark utility, allows programmers to write scripts to automate and customize packet analysis.
This article walks you through setting up Pyshark on a local windows machine, capturing live traffic, and analyzing it. We’ll use practical code examples and explain each step.
This article applies to both Windows and Linux systems but for length only windows setup is thoroughly shown.
Setting Up Pyshark
Before diving into packet capturing, we need to set up Pyshark and its dependencies.
Installing Prerequisites
- Install Python:
- Download and install Python from python.org.
- During installation, ensure “Add Python to PATH” is checked.
2. Install Wireshark with Tshark:
- Windows: Download and install Wireshark from Wireshark’s official site. The specific link for the x64 version.
After downloading the Wireshark installer, unblock it in the download folder and run it.
— In Choose Components window, select Wireshark and TShark.
Note: For our purposes, you can uncheck any extcap tools. Usually, Etwdump is selected but we’re focusing only on network traffic with Pyshark, thus extcap is not required.

— In Additional Tasks window, select Wireshark Start Menu, Wireshark Desktop and Associate File Extensions.

— Select the default installation folder in the Install Location window.

— Select Install Npcap 1.78 in the Packet Capture window.

Note: Npcap is an essential component for capturing packets on Windows. It serves as a packet capture driver and library, enabling tools like Wireshark and Pyshark to interface with your network adapter. Version 1.78 is a stable and compatible choice.
— Unselect USB Capture in the USB Capture window. Press Install to install Wireshark with TShark.

Note: USBPcap is a tool that enables packet capturing from USB devices on your Windows machine. It’s often used to debug or analyze USB communications, such as those between your computer and peripherals like keyboards, mice, USB drives, or other connected devices. We are focusing our efforts on traffic captures.
— During Wireshark install you will see the Npcap Setup window. Select all options and press Install.
Note: This window halts the Wireshark installation (Wireshark’s installation window may be underneath). Select all options, then install.

Follow the remaining steps to complete each installation and reboot the machine.
When the machine reboots, setup your virtual environment:
Setting Up the Environment
Before diving into the code, create a virtual environment to keep the project dependencies isolated.
On Windows:
python -m venv pyshark_env
pyshark_env\Scripts\activate
pip install pyshark
On Linux:
python3 -m venv pyshark_env
source pyshark_env/bin/activate
pip install pyshark
Next add TShark as a temporary environment variable (as shown below). Then run the command tshark — version.
$env:Path += “;C:\Program Files\Wireshark\”

Or you can permanently add TShark to PATH like this:
Press Win + S and type Environment Variables
, then select Edit the system environment variables.
In the System Properties window, click Environment Variables.
- Under System Variables, find the
Path
variable and click Edit. - Add the following to the list:
C:\Program Files\Wireshark\
- Click OK to save and close all dialogs.
- Restart your terminal (VS Code included) for the changes to take effect.
Capturing Live Traffic
Pyshark can capture packets in real time, which is helpful for troubleshooting or monitoring network activity.
Identifying Your Network Interface
To capture packets, you need to know your network interface name:
- Windows: Run the following command:
tshark -D
Example output:
1. \Device\NPF_{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX} (Wi-Fi)
2. \Device\NPF_{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX} (Ethernet)
Linux: Install TShark using your package manager:
sudo apt install tshark # For Ubuntu/Debian
sudo yum install wireshark # For CentOS/Red Hat
- Use the name corresponding to your active connection (e.g., “Wi-Fi”). The text in () is the name.
- Linux: Use
tshark -D
orifconfig
to list interfaces (e.g.,eth0
orwlan0
).
Writing a Live Capture Script
Create a file named live_capture.py
in your project directory and add the following code:
import pyshark
# Replace 'Wi-Fi' with your network interface name
interface = 'Wi-Fi'
capture = pyshark.LiveCapture(interface=interface)
print("Starting packet capture... Press Ctrl+C to stop.")
try:
for packet in capture.sniff_continuously(packet_count=5):
print(f"Packet captured: {packet}")
except KeyboardInterrupt:
print("\nCapture stopped.")
Explanation:
pyshark.LiveCapture(interface='Wi-Fi')
initializes a live packet capture on the specified interface.sniff_continuously(packet_count=5)
captures packets continuously, stopping after five packets.- Results are printed in a raw format but give you an idea of packet activity.
Run the script:
python live_capture.py
Sample Output:
Starting packet capture... Press Ctrl+C to stop.
Packet captured: <PACKET TCP: 192.168.1.2 -> 192.168.1.1>
Packet captured: <PACKET UDP: 192.168.1.3 -> 8.8.8.8>
Packet captured: <PACKET ICMP: 192.168.1.4 -> 192.168.1.1>
Analyzing Saved PCAP Files
If you want to analyze traffic at your convenience, you can save it as a PCAP file and process it later.
Saving Captures to a File
Modify live_capture.py
to save packets to a PCAP file:
import pyshark
interface = 'Wi-Fi'
output_file = 'capture.pcap'
capture = pyshark.LiveCapture(interface=interface, output_file=output_file)
print(f"Saving packets to {output_file}... Press Ctrl+C to stop.")
try:
capture.sniff(packet_count=10)
print(f"Capture complete. Packets saved to {output_file}.")
except KeyboardInterrupt:
print("\nCapture stopped.")
Run the script and view the file in Wireshark for visual analysis.
Reading PCAP Files with Pyshark
Create a new script, read_pcap.py
:
import pyshark
file_path = 'capture.pcap'
capture = pyshark.FileCapture(file_path)
print("Reading packets from file...")
for packet in capture:
print(f"Packet: {packet}")
Explanation:
pyshark.FileCapture(file_path)
loads packets from the specified PCAP file.- The script iterates through packets, printing details for each one.
Run the script:
python read_pcap.py
Filtering and Parsing Packet Data
Filters allow you to focus on specific traffic, such as HTTP or DNS:
import pyshark
interface = 'Wi-Fi'
capture = pyshark.LiveCapture(interface=interface, bpf_filter='tcp port 80') # HTTP traffic
print("Capturing HTTP traffic...")
for packet in capture.sniff_continuously(packet_count=5):
try:
print(f"Source IP: {packet.ip.src}, Destination IP: {packet.ip.dst}")
except AttributeError:
print("No IP layer found.")
A few Real-world examples you can run on your home network.
1. Detect Devices on Your Network
Use Pyshark to identify all devices (IP addresses) communicating on your network.
import pyshark
# Replace 'Wi-Fi' with your network interface
capture = pyshark.LiveCapture(interface='Wi-Fi')
print("Scanning for active devices on the network...")
devices = set()
try:
for packet in capture.sniff_continuously(packet_count=50): # Adjust packet count if needed
try:
src_ip = packet.ip.src
dst_ip = packet.ip.dst
devices.add(src_ip)
devices.add(dst_ip)
except AttributeError:
continue # Skip packets without IP layer
print("Active devices detected on the network:")
for device in devices:
print(device)
except KeyboardInterrupt:
print("\nScan stopped.")
Output:
Scanning for active devices on the network...
Active devices detected on the network:
192.168.1.1
192.168.1.101
192.168.1.102
192.168.1.103
2. Monitor Traffic to a Specific Website
If you suspect someone is visiting a specific website (e.g., example.com
), use Pyshark to filter DNS queries or HTTP traffic.
import pyshark
capture = pyshark.LiveCapture(interface='Wi-Fi', display_filter='dns')
print("Monitoring DNS queries... Press Ctrl+C to stop.")
try:
for packet in capture.sniff_continuously():
try:
if 'example.com' in packet.dns.qry_name:
print(f"Detected DNS query for: {packet.dns.qry_name}")
except AttributeError:
continue # Skip packets without DNS layer
except KeyboardInterrupt:
print("\nMonitoring stopped.")
Output:
Monitoring DNS queries... Press Ctrl+C to stop.
Detected DNS query for: www.example.com
3. Identify High-Bandwidth Users
Monitor traffic on your home network and flag devices that send or receive large amounts of data.
import pyshark
from collections import defaultdict
# Replace 'Wi-Fi' with your network interface
capture = pyshark.LiveCapture(interface='Wi-Fi')
print("Monitoring traffic for high-bandwidth users... Press Ctrl+C to stop.")
traffic = defaultdict(int) # Dictionary to store traffic volume per IP
try:
for packet in capture.sniff_continuously(packet_count=100):
try:
src_ip = packet.ip.src
dst_ip = packet.ip.dst
packet_len = int(packet.length)
# Track traffic per device
traffic[src_ip] += packet_len
traffic[dst_ip] += packet_len
except AttributeError:
continue
print("\nTraffic Summary (Bytes Transferred):")
for ip, total_bytes in traffic.items():
print(f"{ip}: {total_bytes} bytes")
except KeyboardInterrupt:
print("\nMonitoring stopped.")
Output:
Traffic Summary (Bytes Transferred):
192.168.1.1: 50234 bytes
192.168.1.102: 128394 bytes
192.168.1.103: 9832 bytes
4. Detect Unauthorized Devices
Flag unknown IP addresses (not in your known list of devices) on your network.
import pyshark
# List of known devices (update with your network's IPs)
known_devices = {'192.168.1.1', '192.168.1.101', '192.168.1.102'}
# Replace 'Wi-Fi' with your network interface
capture = pyshark.LiveCapture(interface='Wi-Fi')
print("Monitoring for unauthorized devices... Press Ctrl+C to stop.")
try:
for packet in capture.sniff_continuously(packet_count=50):
try:
src_ip = packet.ip.src
dst_ip = packet.ip.dst
# Check for unknown devices
if src_ip not in known_devices:
print(f"Unauthorized device detected: {src_ip}")
if dst_ip not in known_devices:
print(f"Unauthorized device detected: {dst_ip}")
except AttributeError:
continue
except KeyboardInterrupt:
print("\nMonitoring stopped.")
Output:
Unauthorized device detected: 192.168.1.105
Unauthorized device detected: 192.168.1.110
5. Analyze Specific Protocol Traffic (e.g., HTTP or HTTPS)
Use TShark or Pyshark to capture and filter traffic for a specific protocol like HTTP.
Using TShark:
192.168.1.102 example.com
192.168.1.103 api.someapi.com
Using Pyshark:
import pyshark
capture = pyshark.LiveCapture(interface='Wi-Fi', display_filter='http')
print("Capturing HTTP traffic... Press Ctrl+C to stop.")
try:
for packet in capture.sniff_continuously(packet_count=10):
try:
print(f"HTTP Request from {packet.ip.src} to {packet.http.host}")
except AttributeError:
continue
except KeyboardInterrupt:
print("\nCapture stopped.")
Output:
HTTP Request from 192.168.1.102 to www.example.com
HTTP Request from 192.168.1.103 to api.someapi.com
6. Save and Automate Packet Capture
Save packets to a file for later analysis or review.
import pyshark
output_file = 'home_capture.pcap'
capture = pyshark.LiveCapture(interface='Wi-Fi', output_file=output_file)
print(f"Saving packets to {output_file}... Press Ctrl+C to stop.")
try:
capture.sniff(packet_count=100) # Adjust packet count as needed
print(f"Capture complete. Packets saved to {output_file}.")
except KeyboardInterrupt:
print("\nCapture stopped.")
You can then open home_capture.pcap
in Wireshark for detailed analysis.
Why Use TShark or Pyshark Over Wireshark?
While Wireshark is excellent for interactive exploration:
- Pyshark allows Automation: Pyshark can automate monitoring and alerting, saving you from manually filtering packets.
- Python Scripting: Pyshark makes it easy to write custom tools for specific tasks.
- Batch Processing: TShark/Pyshark can handle large-scale data analysis more efficiently in a headless environment.
Thank you for reading this article. I hope you found it helpful and informative. If you have any questions, or if you would like to suggest new Python code examples or topics for future tutorials, please feel free to reach out. Your feedback and suggestions are always welcome!
Happy coding!
C. C. Python Programming
You can also find this at Medium.com