2

大家好。

我正在编写一个脚本来定期监视与端口的连接(在本例中为 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 '================================='"
4

3 回答 3

4

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

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 格式,但我相信如果需要,你可以将它改回原形。

于 2013-09-28T02:38:26.800 回答
2

这更像是一个评论而不是一个答案,因为我不打算将命令传递给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}'
于 2013-09-28T03:48:08.850 回答
1

引自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.
于 2013-09-28T02:39:15.853 回答