From 455d4d75512a7cfac647e6983fc5a3b8c2b29b4f Mon Sep 17 00:00:00 2001 From: Franziska Kunsmann Date: Sun, 6 Jun 2021 17:59:58 +0200 Subject: [PATCH] bundles/sshmon: fix occasional KeyErrors in check_cpu_stats --- bundles/sshmon/files/check_cpu_stats | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/bundles/sshmon/files/check_cpu_stats b/bundles/sshmon/files/check_cpu_stats index d774773..36e5ae3 100644 --- a/bundles/sshmon/files/check_cpu_stats +++ b/bundles/sshmon/files/check_cpu_stats @@ -5,7 +5,16 @@ from subprocess import check_output from sys import exit try: - top_output = check_output("top -b -n1 -d1 | grep -i '^\%cpu'", shell=True).decode('UTF-8').split(': ', 2)[1].strip() + top_output = None + + for line in check_output(['top', '-b', '-n1', '-d1']).decode('UTF-8').splitlines(): + if line.lower().strip().startswith('%cpu'): + top_output = line.lower().split(':', 2)[1] + break + + if not top_output: + print('%cpu not found in top output') + exit(3) cpu_usage = {} for value, identifier in findall('([0-9\.\,]{3,5}) ([a-z]{2})', top_output):