在大多数服务(例如 privoxy)中,有一种简洁的方法来获取服务状态:
ps -C [servicename]
然后通过检查退出代码($?)
:0:服务正在运行 1:未运行 ufw 中不是这种情况(未被识别为服务?)sudo service ufw status
无论 ufw 是否正在运行,它总是以 0 退出。有没有建议通过用于检查 ufw 状态的命令的退出代码以编程方式获取 ufw?
答案1
由于返回的退出代码sudo ufw status
始终为 0,因此您只需要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