import pyshark
cap = pyshark.FileCapture('/tmp/mycapture.cap')
cap
<FileCapture /tmp/mycapture.cap (589 packets)>
print cap[0]
Packet (Length: 698)
Layer ETH:
Destination: BLANKED
Source: BLANKED
Type: IP (0x0800)
Layer IP:
Version: 4
Header Length: 20 bytes
Differentiated Services Field: 0x00 (DSCP 0x00: Default; ECN: 0x00: Not-ECT (Not ECN-Capable Transport))
Total Length: 684
Identification: 0x254f (9551)
Flags: 0x00
Fragment offset: 0
Time to live: 1
Protocol: UDP (17)
Header checksum: 0xe148 [correct]
Source: BLANKED
Destination: BLANKED
...
Other options
param keep_packets: Whether to keep packets after reading them via next(). Used to conserve memory when reading large caps.
param input_file: Either a path or a file-like object containing either a packet capture file (PCAP, PCAP-NG..) or a TShark xml.
param display_filter: A display (wireshark) filter to apply on the cap before reading it.
param only_summaries: Only produce packet summaries, much faster but includes very little information
param disable_protocol: Disable detection of a protocol (tshark > version 2)
param decryption_key: Key used to encrypt and decrypt captured traffic.
param encryption_type: Standard of encryption used in captured traffic (must be either 'WEP', 'WPA-PWD', or 'WPA-PWK'. Defaults to WPA-PWK.
param tshark_path: Path of the tshark binary
Reading from a live interface:
capture = pyshark.LiveCapture(interface='eth0')
capture.sniff(timeout=50)
capture
<LiveCapture (5 packets)>
capture[3]
<UDP/HTTP Packet>
for packet in capture.sniff_continuously(packet_count=5):
print('Just arrived:', packet)
Other options
param interface: Name of the interface to sniff on. If not given, takes the first available.
param bpf_filter: BPF filter to use on packets.
param display_filter: Display (wireshark) filter to use.
param only_summaries: Only produce packet summaries, much faster but includes very little information
param disable_protocol: Disable detection of a protocol (tshark > version 2)
param decryption_key: Key used to encrypt and decrypt captured traffic.
param encryption_type: Standard of encryption used in captured traffic (must be either 'WEP', 'WPA-PWD', or 'WPA-PWK'. Defaults to WPA-PWK).
param tshark_path: Path of the tshark binary
param output_file: Additionally save captured packets to this file.
Reading from a live interface using a ring buffer
for packet in capture.sniff_continuously(packet_count=5):
print('Just arrived:', packet)
Other options
param ring_file_size: Size of the ring file in kB, default is 1024
param num_ring_files: Number of ring files to keep, default is 1
param ring_file_name: Name of the ring file, default is /tmp/pyshark.pcap
param interface: Name of the interface to sniff on. If not given, takes the first available.
param bpf_filter: BPF filter to use on packets.
param display_filter: Display (wireshark) filter to use.
param only_summaries: Only produce packet summaries, much faster but includes very little information
param disable_protocol: Disable detection of a protocol (tshark > version 2)
param decryption_key: Key used to encrypt and decrypt captured traffic.
param encryption_type: Standard of encryption used in captured traffic (must be either 'WEP', 'WPA-PWD', or 'WPA-PWK'. Defaults to WPA-PWK).
param tshark_path: Path of the tshark binary
param output_file: Additionally save captured packets to this file.
Reading from a live remote interface:
Assistant
capture = pyshark.RemoteCapture('192.168.1.101', 'eth0')
capture.sniff(timeout=50)
capture
Other options
param remote_host: The remote host to capture on (IP or hostname). Should be running rpcapd.
param remote_interface: The remote interface on the remote machine to capture on. Note that on windows it is not the device display name but the true interface name (i.e. \Device\NPF_..).
param remote_port: The remote port the rpcapd service is listening on
param bpf_filter: A BPF (tcpdump) filter to apply on the cap before reading.
param only_summaries: Only produce packet summaries, much faster but includes very little information
param disable_protocol: Disable detection of a protocol (tshark > version 2)
param decryption_key: Key used to encrypt and decrypt captured traffic.
param encryption_type: Standard of encryption used in captured traffic (must be either 'WEP', 'WPA-PWD', or 'WPA-PWK'. Defaults to WPA-PWK).
param tshark_path: Path of the tshark binary
Accessing packet data:
Data can be accessed in multiple ways. Packets are divided into layers, first you have to reach the appropriate layer and then you can select your field.
All of the following work:
packet['ip'].dst
192.168.0.1
packet.ip.src
192.168.0.100
packet[2].src
192.168.0.100
To test whether a layer is in a packet, you can use its name:
'IP' in packet
True
To see all possible field names, use the packet.layer.field_names attribute (i.e. packet.ip.field_names) or the autocomplete function on your interpreter.
You can also get the original binary data of a field, or a pretty description of it:
p.ip.addr.showname
Source or Destination Address: 10.0.0.10 (10.0.0.10)
And some new attributes as well:
p.ip.addr.int_value
167772170
p.ip.addr.binary_value
b'\n\x00\x00\n'
Decrypting packet captures
Pyshark supports automatic decryption of traces using the WEP, WPA-PWD, and WPA-PSK standards (WPA-PWD is the default).
cap1 = pyshark.FileCapture('/tmp/capture1.cap', decryption_key='password')
cap2 = pyshark.LiveCapture(interface='wi0', decryption_key='password', encryption_type='wpa-psk')
A tuple of supported encryption standards, SUPPORTED_ENCRYPTION_STANDARDS, exists in each capture class.
pyshark.FileCapture.SUPPORTED_ENCRYPTION_STANDARDS
('wep', 'wpa-pwd', 'wpa-psk')
pyshark.LiveCapture.SUPPORTED_ENCRYPTION_STANDARDS
('wep', 'wpa-pwd', 'wpa-psk')
Reading from a file using a display filter
Pyshark display filters can be helpful in analyzing application focused traffic. BPF filters do not offer as much flexibility as Wireshark's display filters.
Creating a Windows GUI application that monitors network usage per application—including current download/upload speeds and cumulative traffic—requires careful consideration, especially when mapping network packets to specific processes. While pyshark is a powerful library for packet analysis, it doesn't inherently provide mappings between network traffic and the processes generating that traffic on Windows.
To achieve your goal, you'll need to combine pyshark with other tools and libraries, such as psutil, to map network connections to processes. Here's a comprehensive guide to help you build this application using Python, PySide6, and pyshark.
Overview of the Approach
Packet Capturing: Use pyshark to capture network packets in real-time.
Process Mapping: Utilize psutil to map active network connections to their associated processes.
Data Aggregation: Calculate current upload/download speeds and cumulative traffic for each process.
GUI Development: Create a user-friendly interface with PySide6 to display the information and provide sorting options.
Prerequisites
Before diving into the code, ensure you have the necessary libraries installed:
bash
pip install pyshark psutil PySide6
Note:
Running packet capture on Windows may require administrative privileges.
Ensure Wireshark is installed on your system, as pyshark relies on tshark.
Step-by-Step Implementation
1. Packet Capturing with Pyshark
pyshark allows you to capture and analyze network packets. However, it doesn't provide per-process information. We'll use it to capture packets and extract relevant connection details (like IP addresses and ports).
python
import pyshark
# Initialize a live capture on a specific interface
capture = pyshark.LiveCapture(interface='YOUR_NETWORK_INTERFACE')
Replace 'YOUR_NETWORK_INTERFACE' with the actual network interface name (e.g., 'Ethernet', 'Wi-Fi'). You can list available interfaces using:
psutil can list active network connections and map them to process IDs (PIDs). We'll periodically fetch these connections to establish a mapping between connections and processes.
python
import psutil
def get_process_connections():
"""
Returns a dictionary mapping (local_ip, local_port, remote_ip, remote_port) to process info.
"""
connections = {}
for proc in psutil.process_iter(['pid', 'name']):
try:
for conn in proc.connections(kind='tcp'):
if conn.status == psutil.CONN_ESTABLISHED:
key = (conn.laddr.ip, conn.laddr.port, conn.raddr.ip, conn.raddr.port)
connections[key] = {'pid': proc.info['pid'], 'name': proc.info['name']}
except (psutil.NoSuchProcess, psutil.AccessDenied):
continue
return connections
3. Aggregating Data
We'll maintain a data structure to keep track of each process's current speeds and cumulative traffic.
python
import time
from collections import defaultdict
class ProcessTraffic:
def __init__(self):
self.data = defaultdict(lambda: {
'download_speed': 0,
'upload_speed': 0,
'download_total': 0,
'upload_total': 0,
'pid': None,
'name': ''
})
self.last_time = time.time()
self.last_bytes = defaultdict(lambda: {'download': 0, 'upload': 0})
def update(self, packet, connections):
# Extract packet information
try:
ip_layer = packet.ip
transport_layer = packet[packet.transport_layer]
src_ip = ip_layer.src
dst_ip = ip_layer.dst
src_port = int(transport_layer.srcport)
dst_port = int(transport_layer.dstport)
length = int(packet.length)
except AttributeError:
return # Non-IP packet
key = (src_ip, src_port, dst_ip, dst_port)
reverse_key = (dst_ip, dst_port, src_ip, src_port)
process_info = connections.get(key) or connections.get(reverse_key)
if not process_info:
return
pid = process_info['pid']
name = process_info['name']
current_time = time.time()
elapsed = current_time - self.last_time if self.last_time else 1
self.last_time = current_time
# Update cumulative traffic
if key in connections:
# Download for process
direction = 'download'
else:
# Upload for process
direction = 'upload'
self.data[pid]['pid'] = pid
self.data[pid]['name'] = name
self.data[pid][f'{direction}_total'] += length
# Update speeds
self.data[pid][f'{direction}_speed'] = length / elapsed
def get_active_processes(self):
# Filter processes with non-zero traffic
return {pid: info for pid, info in self.data.items() if
info['download_total'] > 0 or info['upload_total'] > 0}
4. Building the GUI with PySide6
We'll create a GUI that displays the processes in a table with sorting capabilities.
python
Important Considerations:
Threading: Packet capturing with pyshark can block the main thread. It's advisable to run the capture in a separate thread to keep the GUI responsive.
Performance: Continuously capturing and processing packets can be resource-intensive. Optimize by filtering relevant packets (e.g., only TCP/UDP) and limiting processing frequency.
Process Mapping Accuracy: The method of mapping packets to processes via connections isn't foolproof. High-frequency or transient connections may lead to missed mappings.
5. Bringing It All Together
Here's how you can integrate the components and run the application:
Threaded Packet Capture: Implement packet capturing in a separate thread to prevent GUI blocking.
python
import threading
class NetworkMonitorGUI(QWidget):
def __init__(self):
# Existing initialization...
self.capture_thread = threading.Thread(target=self.start_capture, daemon=True)
self.capture_thread.start()
def start_capture(self):
for packet in self.capture.sniff_continuously():
connections = get_process_connections()
self.traffic.update(packet, connections)
Efficient Data Handling: To handle high volumes of packets, consider batch processing or aggregating data at intervals.
User Interface Improvements:
Add indicators for total data usage since startup.
Implement filters to show only upload/download or specific protocols.
Provide options to export data logs.
Error Handling: Enhance the application with robust error handling, especially for permission issues related to packet capturing.
Security Considerations: Ensure the application handles sensitive data responsibly and informs users about necessary permissions.
Limitations
Process-Connection Mapping: Accurately mapping packets to processes on Windows is inherently complex and may not always be accurate.
Performance Overhead: Real-time packet capturing and processing can consume significant system resources, especially on busy networks.
Permissions: Capturing packets typically requires administrative privileges on Windows, which can pose security concerns.
Alternative Approaches
If mapping packets to processes proves too challenging or resource-intensive, consider alternative methods:
Using Windows Performance Counters: Access network I/O counters per process using Windows Performance Counters via libraries like pywin32.
Leveraging ETW (Event Tracing for Windows): ETW can provide detailed network activity per process but requires advanced handling and might not have direct Python bindings.
Third-Party Tools: Integrate existing network monitoring tools that support per-process statistics and interact with them via Python.
Conclusion
Building a network monitoring GUI application on Windows that maps traffic to specific processes involves combining packet capturing with system-level process data. While pyshark, psutil, and PySide6 provide powerful tools to achieve this, be prepared to handle the intricacies of accurate mapping, performance optimization, and permissions management. The outlined approach offers a foundation, but further refinements and optimizations will be necessary to create a robust and reliable application.
Sample Complete Code
Below is a simplified and complete version of the application incorporating threading for packet capturing:
python
Replace 'YOUR_NETWORK_INTERFACE' with your actual network interface name.
Final Thoughts
Building a per-process network monitor on Windows using Python involves integrating multiple libraries and handling system-level intricacies. While the provided guide offers a foundational approach, achieving precise and efficient monitoring may require deeper integration with Windows APIs or leveraging specialized network monitoring tools. Always ensure you handle permissions and data responsibly, especially when dealing with network traffic and process information.