1#!/usr/bin/python
2#
3# bashreadline  Print entered bash commands from all running shells.
4#               For Linux, uses BCC, eBPF. Embedded C.
5#
6# This works by tracing the readline() function using a uretprobe (uprobes).
7#
8# Copyright 2016 Netflix, Inc.
9# Licensed under the Apache License, Version 2.0 (the "License")
10#
11# 28-Jan-2016    Brendan Gregg   Created this.
12
13from __future__ import print_function
14from bcc import BPF
15from time import strftime
16
17# load BPF program
18bpf_text = """
19#include <uapi/linux/ptrace.h>
20int printret(struct pt_regs *ctx) {
21    if (!ctx->ax)
22        return 0;
23
24    char str[80] = {};
25    bpf_probe_read(&str, sizeof(str), (void *)PT_REGS_RC(ctx));
26    bpf_trace_printk("%s\\n", &str);
27
28    return 0;
29};
30"""
31b = BPF(text=bpf_text)
32b.attach_uretprobe(name="/bin/bash", sym="readline", fn_name="printret")
33
34# header
35print("%-9s %-6s %s" % ("TIME", "PID", "COMMAND"))
36
37# format output
38while 1:
39    try:
40        (task, pid, cpu, flags, ts, msg) = b.trace_fields()
41    except ValueError:
42        continue
43    print("%-9s %-6d %s" % (strftime("%H:%M:%S"), pid, msg))
44