1
#!/usr/bin/perl

if (! eval "require LWP::UserAgent;")
{
        $ret = "LWP::UserAgent not found";
}

if ( exists $ARGV[0]) {
        if ($ret)
        {
                print "no ($ret)\n";
                exit 1;
        }

        my $ua = LWP::UserAgent->new(timeout => 5);

        my $response = $ua->request(HTTP::Request->new('GET',$ARGV[0]));
        my @content = split (/\n/, $response->content);

        my $active_connections = -1;
        if ($content[0] =~ /^Active connections:\s+(\d+)\s*$/i) {
                $active_connections = $1;
        }

        my $accepts = -1;
        my $handled = -1;
        my $requests = -1;
        if ($content[2] =~ /^\s+(\d+)\s+(\d+)\s+(\d+)\s*$/) {
                $accepts = $1;
                $handled = $2;
                $requests = $3;
        }

        my $reading = -1;
        my $writing = -1;
        my $waiting = -1;
        if ($content[3] =~ /Reading: (\d+) Writing: (\d+) Waiting: (\d+)\s*$/) {
                $reading = $1;
                $writing = $2;
                $waiting = $3;
        }

        print "nginx_active:$active_connections nginx_reading:$reading nginx_writing:$writing nginx_waiting:$waiting ";
        print "\n";
}

我的 nginx 状态页面:

Active connections: 2 
server accepts handled requests
 2 2 2 
Reading: 0 Writing: 1 Waiting: 1

跑步:

./get_nginx_clients_status.pl http://IP/nginx_status
nginx_active:-1 nginx_reading:-1 nginx_writing:-1 nginx_waiting:-1

我应该得到:

nginx_accepts:113869 nginx_handled:113869 nginx_requests:122594

知道有什么问题吗?

4

1 回答 1

0

您的代码指出:

my $accepts = -1;
my $handled = -1;
my $requests = -1;

你的输出是:

nginx_active:-1 nginx_reading:-1 nginx_writing:-1 nginx_waiting:-1

因此,因为您测试:

$content[2] =~ /^\s+(\d+)\s+(\d+)\s+(\d+)\s*$/

...它$content[2]不包含您的正则表达式所需的信息。您是否尝试过添加print $content[2] . "\n";以帮助调试您的脚本?

调试器

请考虑使用 Perl 调试器。它会很快为您解答明显的问题。

-d使用标志启动脚本。然后一次单步执行您的代码,使用n转到下一行,l列出当前点的代码,并x @content(例如)列出每一步的变量内容。

于 2013-07-09T15:17:33.887 回答