July 30, 2025

Capture Packets Using Python And Pyshark Using Less Than 5 Lines Of Code

 

Capture Packets Using Python And Pyshark Using Less Than 5 Lines Of Code

Now for something completely different…


I think network professionals should be ‘aware’ of coding.  Not necessarily a programmer, but at least be familiar with what can be done.


So I thought why not combine 2 of my favorite things; python and capturing packets.


I wanted to show how easy it is to capture packets using Python, so I put together a tiny PyShark example—literally just a few lines of code. My whole point is that network folks don’t need to be full‑blown programmers, but we should be aware of what coding can do for us. Python is simple enough that even if you’re not a developer, you can still automate useful stuff like packet captures without breaking a sweat.

To get started, I just install Python and then run pip install pyshark. Once that’s done, I open a text editor and write a super‑minimal script: import PyShark, create a LiveCapture on an interface, sniff for a second, and print the capture. The funny part is that the script is intentionally crude—it’s designed to throw an error so I can see the list of available interfaces. It’s a hacky trick, but it works every time.

When the script errors out, PyShark dumps all the interfaces, and I just grab the one I need. On Windows, that usually looks like a long \\Device\\NPF_{GUID} string. I copy that exact interface name—double backslashes and all—and drop it into the script. Once the interface is correct, PyShark can actually capture packets instead of just complaining.

After that, I expand the script a bit so it can save packets to a file. I set up a new LiveCapture with the interface and an output filename, then tell it to sniff for either a set amount of time or a specific packet count. In the example, I capture 100 packets and save them into a test.pcapng file. It’s still only a handful of lines, but now it’s doing something genuinely useful.

By the end, I’ve shown that you can capture packets with Python in basically no time. It’s simple, it’s flexible, and it’s a great way for network people to dip their toes into coding. You don’t have to be a developer—you just need to know enough to make your tools work for you. And honestly, it’s fun messing around with this stuff.

For example, here is the output from my script ,

\Device\NPF_{82C048B7-BF6D-4B92-BDFA-872CFC8F7077}

Killer

You need to put \\Device\\NPF_{82C048B7-BF6D-4B92-BDFA-872CFC8F7077}

In my script and make sure you have 2 \\’s

Here is my new code that will capture 100 packets and save it in a test.pcapng

import pyshark

capture = pyshark.LiveCapture(interface='\\Device\\NPF_{82C048B7-BF6D-4B92-BDFA-872CFC8F7077}',output_file='./test.pcapng')

# capture for 5 seconds and stop

# capture.sniff(timeout=5)

#capture 100 packets and stop

capture.sniff(packet_count=100)

capture

Have fun you future coders  😉



Popular post in the past 30 days