Linux watch 命令在脚本中不起作用

crs*_*ezf 2 linux bash shell ubuntu debian

大家好。

我正在编写一个脚本来定期监视与端口的连接(在本例中为 80)。

我写了这个简短的脚本。

echo '=================================';a=`sudo lsof -i :80`;echo $a | awk '{print $1," ",$2," ",$3," ",$8}'; b=`echo $a | wc -l`; b=$(($b - 1));echo Total SSH Connections: $b;echo '================================='
Run Code Online (Sandbox Code Playgroud)

输出是:

=================================  
COMMAND   PID   USER   NODE  
acwebseca   90   root   TCP  
acwebseca   90   root   TCP  
acwebseca   90   root   TCP  
acwebseca   90   root   TCP  
acwebseca   90   root   TCP  
acwebseca   90   root   TCP  
acwebseca   90   root   TCP  
acwebseca   90   root   TCP  
acwebseca   90   root   TCP  
acwebseca   90   root   TCP  
acwebseca   90   root   TCP  
acwebseca   90   root   TCP  
acwebseca   90   root   TCP  
acwebseca   90   root   TCP  
acwebseca   90   root   TCP  
acwebseca   90   root   TCP  
acwebseca   90   root   TCP  
acwebseca   90   root   TCP  
acwebseca   90   root   TCP  
Total SSH Connections: 19  
=================================  
Run Code Online (Sandbox Code Playgroud)

但是,当尝试使用 watch 命令时,它会引发错误,并且当我取消命令时我看不到输出,我会看到如下错误:

sh: PID: command not found
                          sh: -c: line 1: syntax error near unexpected token `('
                                                                                sh: -c: line 1: `acwebseca  90 root   37u  IPv4 0x81ae738f91e7bed9      0t0  TCP 192.168.0.11:49915->108.160.163.33:http (ESTABLISHED)'
Run Code Online (Sandbox Code Playgroud)

我怎样才能解决这个问题。

watch -n 2 "echo '=================================';a=`sudo lsof -i :80`;echo $a | awk '{print $1," ",$2," ",$3," ",$8}'; b=`echo $a | wc -l`; b=$(($b - 1));echo Total SSH Connections: $b;echo '================================='"
Run Code Online (Sandbox Code Playgroud)

Joh*_*nck 5

如果将脚本写入文件并执行它,它就会起作用。那么它不一定是一个丑陋的俏皮话,但可以看起来像这样:

echo '================================='
a=`sudo lsof -i :80`
echo $a | awk '{print $1," ",$2," ",$3," ",$8}'
b=`echo $a | wc -l`
b=$(($b - 1))
echo Total SSH Connections: $b
echo '================================='
Run Code Online (Sandbox Code Playgroud)

只需将其放入文件中,然后运行即可watch my-script.sh。这解决了问题,同时使代码可读。

编辑:如果你真的想要一句台词,这是一个坏主意,你可以尝试这个:

watch 'echo =================================;a=`lsof -i :80`;echo $a | awk "{print \$1, \$2, \$3, \$8}"; b=`echo $a | wc -l`; b=$(($b - 1));echo Total SSH Connections: $b;echo ================================='
Run Code Online (Sandbox Code Playgroud)

基本上我调整了引用以使其正常运行;我可能稍微搞乱了 awk 格式,但我确信如果需要的话您可以将其恢复原状。

  • 你为什么想要这样做?根据我更好的判断,我在我的答案中添加了一个例子。 (2认同)