如何解析netstat输出并提取第四列

时间:2017-10-07 20:38:52

标签: regex perl

如何解析netstat的第四列而不是第一列?

另外,如果连接数低于预期的IP数量,如何使用mailx发送电子邮件提醒?

代码

#!/usr/bin/perl
use strict;
use warnings;

my %minimum = (
    '101.101.101.101:2000' => 2,
    '101.101.101.102:3000' => 5,
);

my %count;

open my $fh, '-|', 'netstat -an' or die "could not run netstat: $!";

while( <$fh> ) {
    next unless /^([0-9.]+:\d+000) /;
    $count{$1}++;
}

close $fh;

while ( my ($ip_port, $min) = each %minimum ) {
    $count{$ip_port} ||= 0;
    next if $count{$ip_port} >= $min;
    print "$ip_port: need $min connections, found only  $count{$ip_port}\n";
}

以下是netstat

的输出
tcp 0 0 ::ffff:101.101.101.101:2000 ::ffff:10.151.89.57:8030 ESTABLISHED

我试图让上面的脚本看第四列

ffff:101.101.101.101:2000

如果该地址没有出现两次,则提醒。

10.101.101.102:3000的相同概念在netstat输出的第4列中应出现不少于5次。

2 个答案:

答案 0 :(得分:2)

如果你问为什么你的代码不起作用,那很清楚,因为你将你的正则表达式模式/^([0-9.]+:\d+000) /锚定到字符串的开头。您的示例数据中没有IPv6地址。

请通过编辑您的问题添加信息。评论中几乎没用。

以下是我编写代码的方法。没有理由打开管道的句柄

#!/usr/bin/perl

use strict;
use warnings 'all';

my %minimum = (
    '101.101.101.101:2000' => 2,
    '101.101.101.102:3000' => 5,
);

my %count;

/\b([0-9.]+:\d+000)\b/ and ++$count{$1} for `netstat -an`;

while ( my ( $ip_port, $min ) = each %minimum ) {
    my $n = $count{$ip_port} // 0;
    print "$ip_port: need $min connections, found only  $n\n" if $n < $min;
}

答案 1 :(得分:0)

假设一行和列由空格分隔,
要获得第4列,请使用这样的正则表达式:

/^\s*(?:\S+\s+){3}(\S+)/

 ^ \s*                  # BOS
 (?: \S+ \s+ ){3}       # 3 columns
 ( \S+ )                # (1), 4th column

以上是一般形式 如果您有第4列的特定表格,那将是
像这样的东西

^\s*(?:\S+\s+){3}\S*?([0-9.]+:\d+000)

https://regex101.com/r/IWmbdh/1