如何檢查 ufw 是否正在以程式設計方式運行

如何檢查 ufw 是否正在以程式設計方式運行

在大多數服務(例如 privoxy)中,有一種乾淨的方法來獲取服務狀態: ps -C [servicename] 然後透過檢查退出代碼($?): 0:服務正在運行 1:未運行 ufw 中不是這種情況(未識別為服務?)sudo service ufw status無論ufw是否運行,總是以0 退出。有什麼建議可以透過用於檢查 ufw 狀態的命令的退出代碼以編程方式獲取 ufw 嗎?

答案1

由於傳回的退出代碼始終為 0,因此您只需取得狀態值sudo ufw status即可:grep

$ sudo ufw status
Status: inactive
$ sudo ufw status | grep -qw active
$ echo $?
1

要正常工作,您必須使用以下-w選項man grep

   -w, --word-regexp
          Select  only  those  lines  containing  matches  that form whole
          words.  The test is that the matching substring must  either  be
          at  the  beginning  of  the  line,  or  preceded  by  a non-word
          constituent character.  Similarly, it must be either at the  end
          of  the  line  or  followed by a non-word constituent character.
          Word-constituent  characters  are  letters,  digits,   and   the
          underscore.

-q只是安靜模式,沒有任何內容寫入標準輸出

答案2

檢查 UFW 使用狀態

sudo ufw status verbose

輸出類似

my@machine:~$ sudo ufw status verbose
[sudo] password for youruser:
Status: active
Logging: on (low)
Default: deny (incoming), allow (outgoing)
New profiles: skip

相關內容