Tech News
← Back to articles

PythonBPF – Writing eBPF Programs in Pure Python

read original related products more articles

Introduction

Python-BPF offers a new way to write eBPF programs entirely in Python, compiling them into real object files. This project is open-source and available on GitHub and PyPI. I wrote it alongside R41k0u.

Published Library with Future Plans

Python-BPF is a published Python library with plans for further development towards production-ready use.

You can pip install pythonbpf but it’s certainly not at all production ready and the code is hacky at best with more bugs than I could count. (This was a hackathon project afterall. We plan to fix it after we are done with the hackathon.)

The Old Way: Before Python-BPF

Before Python-BPF, writing eBPF programs in Python typically involved embedding C code within multiline strings, often using libraries like bcc . eBPF allows for small programs to run based on kernel events, similar to kernel modules.

Here’s an example of how it used to be:

from bcc import BPF from bcc.utils import printb # define BPF program prog = """ int hello(void *ctx) { bpf_trace_printk("Hello, World! \\ n"); return 0; } """ # load BPF program b = BPF ( text = prog ) b . attach_kprobe ( event = b . get_syscall_fnname ( "clone" ), fn_name = "hello" ) # header print ( " %-18s %-16s %-6s %s " % ( "TIME(s)" , "COMM" , "PID" , "MESSAGE" )) # format output while 1 : try : ( task , pid , cpu , flags , ts , msg ) = b . trace_fields () except ValueError : continue except KeyboardInterrupt : exit () printb ( b " %-18.9f %-16s %-6d %s " % ( ts , task , pid , msg ))

This approach, while functional, meant writing C code within Python, lacking support from modern Python development tools like linters.

... continue reading