Linux Format

Grasp the basics of writing your own eBPF scripts

-

To write your own Python script and take advantage of eBPF you should first have an idea of what you want to achieve. Put simply, you can’t accidental­ly create a Python script that uses eBPF and does the job! The following eBPF script, which is called hwBPF, just prints a static message on the screen every time a new process is created on your Linux system. It’s the simplest form of an eBPF script: #!/usr/bin/env python from bcc import BPF myProgram = “"” int kprobe__sys_clone(void *ctx) { bpf_trace_printk("Hello Linux Format!\\n");

return 0; } “"” BPF(text=myProgram).trace_print()

From the Python code of hwBPF you can see that the C program is kept in the myProgram variable and loaded using the BPF(text=

myProgram) command. The trace_print() Python function is a bcc routine that reads eBPF data and prints it on the screen. The bpf_trace_

printk() function of the C program is a kernel facility for printing. The important thing here is that every C function that begins with kprobe__ tells the kernel that you want to trace the remaining text of its name, which in this case is the sys_clone() system call.

Executing hwBPF will create the following static output every time a process is created on your Linux system: sshd-28566 [000] d... 108550.124908: : Hello Linux Format!

The output of hwBPF is pretty easy to interpret. The first field shows the name of the process that called sys_clone() and the fourth field is the time the event happened. The last field is the static text message. We won’t deal with the second and third fields here.

Despite its simplicity, hwBPF can still be used for checking the activity of a Linux system that seems idle. Additional­ly, you can check the complexity of specific commands by counting the number of output lines they generate.

Newspapers in English

Newspapers from Australia