systemctl status 的輸出較短

systemctl status 的輸出較短

有沒有辦法從 systemctl 狀態獲得更短/自訂的輸出?我實際上只需要在活動行前面加上服務名稱。所以像這樣:

        apache2: active (running) since Thu 2020-02-06 17:20:42 +03; 16min ago
        mongodb: inactive (dead)  since Thu 2020-02-06 17:20:47 +03; 16min ago
rabbitmq-server: active (running) since Thu 2020-02-06 17:20:52 +03; 16min ago
 mongodb-server: active (running) since Thu 2020-02-06 17:20:54 +03; 16min ago
          mysql: active (running) since Thu 2020-02-06 17:20:57 +03; 16min ago

僅具有顏色回饋。但我會接受沒有顏色的。或在兩行加上一個空白行,例如:

● apache2.service - The Apache HTTP Server
   Active: active (running) since Thu 2020-02-06 17:20:42 +03; 16min ago

● mongodb.service - An object/document-oriented database
   Active: inactive (dead) since Thu 2020-02-06 17:20:47 +03; 16min ago

● redis-server.service - Advanced key-value store
   Active: active (running) since Thu 2020-02-06 17:20:52 +03; 16min ago

● rabbitmq-server.service - RabbitMQ Messaging Server
   Active: active (running) since Thu 2020-02-06 17:20:54 +03; 16min ago

● mysql.service - MySQL Community Server
   Active: active (running) since Thu 2020-02-06 17:20:57 +03; 16min ago

順便說一句,這種滿足後者:

systemctl status apache2.service mongodb.service \
redis.service rabbitmq-server.service mysql.service | grep -e Active -e ●

但它搞亂了顏色,沒有空格,我有點希望有一個 systemctl 選項或配置,我可以在其中得到我想要的東西。

答案1

因此,沒有本地方法可以systemctl以這種方式格式化輸出,但我們無論如何都可以透過對管道進行一些創意來做到這一點。

首先,我們需要係統上所有正在運行的服務的清單:

# systemctl -t service --state=running --no-legend --no-pager

accounts-daemon.service                         loaded active running Accounts Service                                               
atd.service                                     loaded active running Deferred execution scheduler                                   
containerd.service                              loaded active running containerd 
...

沒有時間輸出。為了實現這一點,我們必須呼叫systemctl show帶有標誌的單元--property=ActiveEnterTimestamp。例子:

# systemctl show accounts-daemon.service --property=ActiveEnterTimestamp
ActiveEnterTimestamp=Wed 2019-12-11 21:44:50 UTC

現在,如果我們有辦法將該輸出釘到輸出的末端systemctl......我們就可以了!

這是一句醜陋的俏皮話,但它完成了工作:

systemctl -t service --state=running --no-legend --no-pager | cut -d ' ' -f 1 | while read f; do STARTTIME=`systemctl show $f 
--property=ActiveEnterTimestamp | sed 's/ActiveEnterTimestamp=//'`; echo "$f $STARTTIME"; done`

解釋:

  • cut指令按空格分割並從 中取得第一個字段systemctl,即服務名稱。
  • 我們輸入一個 while 循環,將該服務名稱傳送到名為的變數中$f
  • 我們建立一個名為的變量STARTTIME,其中包含systemctl show帶有開始時間標誌的輸出。
  • 我們通常sed會刪除實際的ActiveEnterTimestamp=文本,只給我們時間。
  • 最後,我們將echo服務名稱和清理後的開始時間以空格分隔。

最終輸出如下圖所示:

accounts-daemon.service Wed 2019-12-11 21:44:50 UTC
atd.service Wed 2019-12-11 21:44:48 UTC
containerd.service Wed 2019-12-11 21:44:50 UTC

相關內容