Linux 监视命令在脚本中不起作用



大家好。

我正在做一个脚本,用于定期监视与端口的连接(在本例中为 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 '================================='

输出为:

=================================  
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  
=================================  

但是当尝试使用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)'

我该如何解决这个问题。

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 '================================='"

如果您将脚本写入文件并执行它,它会起作用。 那么它不必是一个可怕的单行,但可以看起来像这样:

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 '================================='

只需将其放入文件中,然后运行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 ================================='

基本上我调整了报价以使其正常运行;我可能稍微搞砸了awk格式,但我相信如果需要,您可以将其恢复原状。

这与其说是答案,不如说是评论,因为我不打算解决将命令传递给watch的问题。 但是格式化注释很难。 您可以通过在 awk 中执行更多操作来大大简化命令:

 sudo lsof -i :80 | awk '
      BEGIN { d="================================="; print d}
      {print $1," ",$2," ",$3," ",$8}'
      END { print "Total SSH Connections:", NR-1; print d}'

引用自man watch

Note that command is given to "sh -c" which means that you may need
to use extra quoting to get the desired effect.  You can disable this
with the -x or --exec option, which passes the command to exec(2) instead.
Note that POSIX option processing is used (i.e., option processing stops
at the first non-option argument).  This means that
flags after command don't get interpreted by watch itself.

最新更新