
我有一個每日腳本,每天晚上從我的所有 RHEL 伺服器檢索硬體統計資料並將其保存到yyyymmdd_daily.log文件。我有其他腳本針對這些文件運行以提取特定數據(即驅動器陣列狀態,硬體狀態,磁碟可用空間等)用於不同的任務。
例子硬體狀態腳本輸出:
#######################
Server: abc
** Fans **
Health: Ok
** Power Supplies **
Redundancy: Full
#######################
Server: bcd
** Fans **
Health: Partial
** Power Supplies **
Redundancy: Half
#######################
Server: cde
** Fans **
Health: Down
** Power Supplies **
Redundancy: None
#######################
etc... for 44 servers
由於很少出現任何失敗,因此我想在運行腳本時對顯示任何類型錯誤的行進行著色。我可以使用 grep 選擇要仔細檢查的行:
./HardwareStatus | grep '^Health\|^Redundancy\|$'
但從這裡開始,我只需要對那些沒有以各自令人滿意的響應結束的仔細檢查的行進行著色:
./HardwareStatus | grep --color=auto -v 'Ok$\|Full$'
我嘗試將行選擇 grep 語句透過管道傳輸到第二個 grep 或使用egrep,但它只會刪除腳本輸出中沒有令人滿意的回應的任何行。
任何幫助將不勝感激。
答案1
您可以使用colorama
Python 中的套件來編寫一個簡單的過濾器(或者可能將其包含在您的 HardwareStatus 腳本中,如果它是用 Python 編寫的)
#!/usr/bin/env python3
import fileinput
from colorama import init, Fore, Back, Style
init()
for line in fileinput.input():
message = line.strip()
if (("Health:" in message and "Ok" not in message) or
("Redundancy:" in message and "Full" not in message)):
print(Back.RED + Fore.YELLOW + message + Style.RESET_ALL)
else:
print(message)
要使用上面的腳本,只需將 HardwareStatus 的輸出透過管道傳遞給它,就像在上面的範例中使用 grep 所做的那樣。
看Colorama 文檔了解詳情。