我创建了以下简单脚本,以便提供所有 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
[email protected]
Failed to get properties: Unit name [email protected] 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
[email protected]
Failed to get properties: Unit name [email protected] 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
.
.
.
答案1
根据您的脚本,我在xargs
a 之前添加了一个管道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, - -
使用格式“最多 X 天”更新作为输出。这会检查状态,如果状态具有日期正则表达式匹配(死的或不活动的服务或其他错误不会有),它将计算日期差异。依赖于dateutils
-包裹大多数发行版都可用。请注意,我的命令使用debian
调用方式dateutils
- 这可能因发行版而异。由于 的条件变化xargs
,这里不需要“黑客” 。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
答案2
您可以通过添加 sed 命令来获取所需的输出
#!/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 |sed "N;s/\n/ /g"