I want to parse the output of w so I can collect current user sessions and record them via telegraf. However, it only provides space separated output and I'm not sure how to reliably parse this without potentially splitting the 'command' field into multiple columns.
Asked
Active
Viewed 34 times
0
Zac Pullar-Strecker
- 101
- 1
-
Using command line tools: `nusers=$( w | head -n 1 l cut "-d," -f2 | awk '{print $1}')` – waltinator Aug 11 '23 at 00:29
-
1The `w` command may not be the best option. You could also use `who` or `users` or read /var/log/utmp directly (see man page for utmp) – user10489 Aug 11 '23 at 01:08
-
@user10489 If there's a way to do it with another command that works, /var/log/utmp intimidates me. I kind of feel like I can't have been the first to want this? – Zac Pullar-Strecker Aug 11 '23 at 04:05
-
@waltinator I don't just want the number of users (or the list). Specifically, I'd love to collect user names, IP addresses, login times, idle times, CPU usage, and the current command. Basically everything except the TTY column. – Zac Pullar-Strecker Aug 11 '23 at 04:06
-
utmp has all of that except cpu usage, idle times, and current command, and `w` is the best source for all those things. I believe it uses fixed width columns, so you could parse it that way probably. I'm not sure how you want to send it to telegraf. – user10489 Aug 11 '23 at 11:32
-
Collect everything, ignore TTY column later. Repeatedly do:`(printf "# date: ";date;w) >>w.$(date "+%F").log`. The log file name changes every day, e.g. `w.2023-08-10.log`, `w.2023-08-11.log`, etc. – waltinator Aug 12 '23 at 04:06