![如何檢查 ufw 是否正在以程式設計方式運行](https://rvso.com/image/1083748/%E5%A6%82%E4%BD%95%E6%AA%A2%E6%9F%A5%20ufw%20%E6%98%AF%E5%90%A6%E6%AD%A3%E5%9C%A8%E4%BB%A5%E7%A8%8B%E5%BC%8F%E8%A8%AD%E8%A8%88%E6%96%B9%E5%BC%8F%E9%81%8B%E8%A1%8C.png)
在大多數服務(例如 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