1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
| import subprocess import threading import time import csv import argparse import os import sys from datetime import datetime import re import fcntl
stop_event = threading.Event()
def user_input_thread(): """A simple thread that waits for the user to press Enter and then sets the stop event.""" input("Tool is running... Press [Enter] to stop and save results.\n") stop_event.set()
def parse_biosnoop_output(raw_data: str) -> (list, list): """Custom parser for biosnoop's output.""" print("Using 'biosnoop' parser...") headers = ["TIME", "COMM", "PID", "DISK", "T", "SECTOR", "BYTES", "LAT(ms)"] data_rows = [] lines = raw_data.strip().split('\n') start_line = 1 if lines and lines[0].strip().startswith("TIME") else 0
for line in lines[start_line:]: if not line.strip(): continue parts = re.split(r'\s+', line.strip(), maxsplit=len(headers)-1) if len(parts) == len(headers): data_rows.append(parts)
return headers, data_rows
def parse_biotop_output(raw_data: str) -> (list, list): """Custom parser for biotop's output, which only processes the final screen.""" print("Using 'biotop' parser...") headers = ["PID", "COMM", "D", "DISK", "I/O", "Kbytes", "AVGms"] data_rows = [] last_header_index = raw_data.rfind("PID") if last_header_index == -1: return headers, []
relevant_data = raw_data[last_header_index:] lines = relevant_data.strip().split('\n')
for line in lines[1:]: line = line.strip() if not line or "Ending" in line: continue parts = re.split(r'\s+', line, maxsplit=len(headers)-1) if len(parts) == len(headers): data_rows.append(parts)
return headers, data_rows
def parse_biopattern_output(raw_data: str) -> (list, list): """Custom parser for biopattern's output.""" print("Using 'biopattern' parser...") headers = ["DISK", "%RND", "%SEQ", "COUNT", "KBYTES"] data_rows = [] last_header_index = raw_data.rfind("DISK") if last_header_index == -1: return headers, []
relevant_data = raw_data[last_header_index:] lines = relevant_data.strip().split('\n')
for line in lines[1:]: line = line.strip() if not line or "Tracing" in line or "Ending" in line: continue parts = re.split(r'\s+', line) if len(parts) == len(headers): data_rows.append(parts)
return headers, data_rows
def parse_histogram_output(raw_data: str, tool_name: str) -> (list, list): """A generic parser for histogram-based tools like biolatency and bitesize.""" print(f"Using '{tool_name}' (histogram) parser...")
if tool_name == "biolatency": headers = ["Disk", "Latency Range", "Unit", "Count", "Distribution"] elif tool_name == "bitesize": headers = ["Size Range (KBytes)", "Count", "Distribution"] else: headers = ["Range", "Count", "Distribution"]
data_rows = [] current_disk = "all" current_unit = "us" if " (us)" in raw_data else "ms"
lines = raw_data.strip().split('\n') for line in lines: line = line.strip() if not line or "Tracing" in line or "Ending" in line: continue
disk_match = re.match(r'disk = (\S+)', line) if disk_match: current_disk = disk_match.group(1) continue
hist_match = re.match(r'(\S+\s*->\s*\S+|\S+)\s*:\s*(\d+)\s*\|(.*)\|', line) if hist_match: groups = hist_match.groups() rng, count, dist = groups[0].strip(), groups[1], groups[2].strip()
if tool_name == "biolatency": data_rows.append([current_disk, rng, current_unit, count, dist]) elif tool_name == "bitesize": data_rows.append([rng, count, dist])
return headers, data_rows
PARSERS = { "biosnoop": parse_biosnoop_output, "biotop": parse_biotop_output, "biopattern": parse_biopattern_output, "biolatency": lambda data: parse_histogram_output(data, "biolatency"), "bitesize": lambda data: parse_histogram_output(data, "bitesize"), }
def main(): """The main function that orchestrates the entire process.""" parser = argparse.ArgumentParser( description="A script to monitor system activity using bcc-tools and save the results to a CSV file.", formatter_class=argparse.RawTextHelpFormatter, epilog=f""" Examples: sudo ./monitor_and_save.py biosnoop sudo ./monitor_and_save.py biopattern -o /tmp/logs sudo ./monitor_and_save.py biolatency
Supported tools: {', '.join(PARSERS.keys())} """ ) parser.add_argument("tool", help="The name of the bcc tool to run.") parser.add_argument("-o", "--output_dir", default=".", help="The directory to save the CSV file (default: current directory).") args = parser.parse_args()
tool_name = args.tool output_dir = args.output_dir
if tool_name not in PARSERS: print(f"Error: Unsupported tool '{tool_name}'. Please choose from: {list(PARSERS.keys())}", file=sys.stderr) sys.exit(1)
if os.geteuid() != 0: print("Error: This script requires root privileges to run bcc-tools. Please use 'sudo'.", file=sys.stderr) sys.exit(1)
tool_path = f"/usr/sbin/{tool_name}-bpfcc" if not os.path.exists(tool_path): print(f"Error: Tool '{tool_path}' not found. Please ensure bcc-tools are installed correctly.", file=sys.stderr) sys.exit(1)
os.makedirs(output_dir, exist_ok=True)
input_thread = threading.Thread(target=user_input_thread) input_thread.start()
command = [tool_path] print(f"Starting: {' '.join(command)}...")
process = subprocess.Popen( command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, encoding='utf-8', errors='ignore', preexec_fn=os.setsid )
stdout_fd = process.stdout.fileno() flags = fcntl.fcntl(stdout_fd, fcntl.F_GETFL) fcntl.fcntl(stdout_fd, fcntl.F_SETFL, flags | os.O_NONBLOCK)
captured_output = "" print("-" * 60) while not stop_event.is_set(): try: chunk = process.stdout.read(4096)
if chunk: print(chunk, end='', flush=True) captured_output += chunk else: if process.poll() is not None: break time.sleep(0.1)
except BlockingIOError: time.sleep(0.1) continue except KeyboardInterrupt: break print("-" * 60)
print("\nStopping the tool...") try: os.killpg(os.getpgid(process.pid), 15) process.wait(timeout=5) except (ProcessLookupError, PermissionError): pass except subprocess.TimeoutExpired: print("Tool did not terminate gracefully, forcing shutdown...") os.killpg(os.getpgid(process.pid), 9)
print("Processing captured data...") full_output = captured_output
parser_func = PARSERS[tool_name] headers, data_rows = parser_func(full_output)
if not data_rows: print("⚠️ Warning: No valid data was parsed. The tool may have run for too short a time.") return
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") output_filename = os.path.join(output_dir, f"{tool_name}_output_{timestamp}.csv")
try: with open(output_filename, 'w', newline='', encoding='utf-8') as csvfile: writer = csv.writer(csvfile) writer.writerow(headers) writer.writerows(data_rows) print(f"✅ Success! Results saved to: {output_filename}") except IOError as e: print(f"❌ Error: Could not write to file {output_filename}. Reason: {e}", file=sys.stderr)
if __name__ == "__main__": main()
|