Getting Uptime or Downtime of Systemd Process Using Systemctl

getting uptime or downtime of systemd process using systemctl?

Using systemctl's property WatchdogTimestamp

 blr8-100-208-Vin:~ # systemctl show novell-nss --property WatchdogTimestamp
WatchdogTimestamp=Tue 2020-11-24 17:30:20 IST

Time since the systemd service was started - Bash

You could use GNU date to convert the ActiveEnterTimestamp value to seconds-since-the-epoch, then subtract the current seconds-since-the-epoch to get the running time in seconds.

servicestartsec=$(date -d "$(systemctl show --property=ActiveEnterTimestamp your-service-here | cut -d= -f2)" +%s)
serviceelapsedsec=$(( $(date +%s) - servicestartsec))

Substitute "your-service-here" for your actual service name.

The first line assigns the start time in seconds by extracting the date portion of systemctl show --property=ActiveEnterTimestamp... (using cut to extract the second =-delimited field) and then passing it to GNU date and asking for output in seconds-since-the-epoch.

The second line simply subtracts that start time from the current time to get an elapsed time in seconds. Divide that as needed to get elapsed minutes, hours, etc.

How to check how many times linux service restarted

If you have logs from that period, you can indeed extract the "Stopped"/"Started" messages from the logs. On nowadays system with systemd, many systems use journalctl, but many systems use something else - you'll have to inspect your specific system on how to query the logs.

Your script could look something along:

 journalctl --since=<date> --until=<another data> UNIT=<service name> SYSLOG_IDENTIFIER=systemd |
awk '
/Started/{ started = 1 }
/Stopped/{ if (started) { started = 0; restarted++; } }
END {
print "It was restarted " restarted "times."
}
'

The regex here are just an example. Better use journalctl -o json and parse the output with jq.



Related Topics



Leave a reply



Submit