Bash

bash + 列印所有啟用的服務在 Linux 機器上正常執行

  • April 6, 2021

我創建了以下簡單腳本,以便提供所有 systemctl 服務的列表以及正常執行時間

我們在 rhel 7.2 機器上執行腳本

#!/bin/bash
for i in ` systemctl list-unit-files | grep enabled | awk '{print $1}' `
do
echo -e $i
systemctl status $i | grep "Active:" |  awk -F";" '{print (NF>1)? $NF : ""}'
done

腳本列印以下範例輸出

accounts-daemon.service
4 months 4 days ago
appdynamics-machine-agent.service
9 months 21 days ago
atd.service
9 months 21 days ago
auditd.service
9 months 21 days ago
autovt@.service
Failed to get properties: Unit name autovt@.service is missing the instance name.
bluetooth.service
9 months 21 days ago
chronyd.service
2 days ago
crond.service
7 months 25 days ago
dbus-org.bluez.service
9 months 21 days ago
dbus-org.freedesktop.ModemManager1.service
9 months 21 days ago
display-manager.service
9 months 21 days ago
dmraid-activation.service
9 months 21 days ago
gdm.service
9 months 21 days ago

而預期的輸出應該如下

accounts-daemon.service      4 months 4 days ago
appdynamics-machine-agent.service       9 months 21 days ago
atd.service       9 months 21 days ago
auditd.service       9 months 21 days ago
autovt@.service
Failed to get properties: Unit name autovt@.service is missing the instance name.
bluetooth.service    9 months 21 days ago
chronyd.service     2 days ago
crond.service      7 months 25 days ago
dbus-org.bluez.service       9 months 21 days ago
dbus-org.freedesktop.ModemManager1.service       9 months 21 days ago
display-manager.service      9 months 21 days ago
dmraid-activation.service      9 months 21 days ago
gdm.service      9 months 21 days ago

我要歸檔的最佳輸出如下,並且它更具可讀性

accounts-daemon.service,up 124 days
appdynamics-machine-agent.service,up 234 days
atd.service,up 234 days
.
.
.

使用您的腳本,我通過xargs(之前awk)添加了一個管道以抑制錯誤輸出,然後僅用於paste獲取所需的格式:

#!/bin/bash
for i in ` systemctl list-unit-files | grep enabled | awk '{print $1}' `
do
echo -e $i
systemctl status $i | grep "Active:" |  xargs | awk -F";" '{print (NF>1)? $NF : ""}'
done | paste -d, - - 

使用格式“up X days”作為輸出進行更新。這將檢查狀態,如果狀態具有日期正則表達式匹配(哪些死或不活動的服務或其他錯誤不會有),它將計算日期差異。依賴於可用於大多數發行版的 -package dateutils請注意,我的命令使用debian呼叫方式dateutils- 這可能因發行版而異。這裡xargs不需要“hack”,sed因為$status.

#!/bin/bash
for i in ` systemctl list-unit-files | grep enabled | awk '{print $1}' `
do
echo $i
dateregex='20[0-9][0-9]-[0-1][0-9]-[0-3][0-9] [0-2][0-9]:[0-5][0-9]:[0-5][0-9]'
status=$(systemctl status $i | grep "Active:" | sed "s/.*\($dateregex\).*/\1/")
if [[ "$status" =~ $dateregex ]] ; then
   status=$(dateutils.ddiff -f "up %d days" "$status" now)
fi
echo "$status"
done | paste -d, - - 

輸出:

syslog.service,up 82 days
systemd-fsck-root.service,up 82 days
systemd-timesyncd.service,up 13 days
triggerhappy.service,up 82 days
wpa_supplicant.service,up 82 days

引用自:https://unix.stackexchange.com/questions/643739