yllplay 发表于 2018-8-31 12:23:58

perl 获取监控数据


[*]#!/usr/bin/perl -w
[*]
[*]use strict;
[*]use utf8;
[*]use LWP::Simple;
[*]use DBI;
[*]
[*]my $dsn = 'DBI:mysql:database=monitor;host=localhost;port=3306';
[*]my $dbh = DBI->connect($dsn,'root','test',{PrintError=>0,RaiseError=>1})
[*]                        or die "Can't connect to mysql" . DBI->errstr;
[*]
[*]my $table = qq/CREATE TABLE IF NOT EXISTS monitor (
[*]               room char(20) not null,
[*]               in_bytes varchar(100) not null,
[*]               out_bytes varchar(100) not null,
[*]               date timestamp not null
[*]               )
[*]            /;
[*]
[*]my $sth = $dbh->prepare($table);
[*]   $sth->execute();
[*]   $sth->finish();
[*]
[*]while (1) {
[*]       my $url = shift || "http://xxx.xxx.xxx.xxx";
[*]       my $content = get $url;
[*]       my @url = split /\n/,$content;
[*]       my ( $i,$str ) = ( 0,\@url );
[*]       print scalar localtime,"\n";
[*]
[*]       while ( $i < scalar @$str ) {
[*]
[*]             if ( @$str[$i++] =~ /杭州机房1|杭州机房2|上海机房1|上海机房2/ ) {
[*]               binmode STDOUT,'encoding(utf8)';
[*]               my $room = $&;
[*]               print STDOUT &quot;$&\n&quot;;
[*]               $i += 16;
[*]               my ($in) = @$str[$i++] =~ /(?:.*)\>(\S*\s*\S*).*\/;
[*]               printf '%s',&quot;\tCurrent In: $1\t&quot;;
[*]               $i += 5;
[*]               my ($out) = @$str[$i++] =~ /(?:.*)\>(\S*\s*\S*).*\/;
[*]               printf '%s',&quot;Current Out: $1\n\n&quot;;
[*]               my ($sec,$min,$hour,$day,$month,$year) = (localtime(time));
[*]               $month++;$year+=1900;
[*]               my $date = sprintf &quot;%04d-%02d-%02d %d:%d:%d&quot;,$year,$month,$day,$hour,$min,$sec;
[*]
[*]               my $data = qq/INSERT INTO monitor VALUES
[*]                              (&quot;$room&quot;,&quot;$in&quot;,&quot;$out&quot;,&quot;$date&quot;)/;
[*]                  $sth = $dbh->do($data);
[*]             }
[*]
[*]       }
[*]
[*]print '-' x 70,&quot;\n&quot;;
[*]sleep 900;
[*]
[*]}
[*]
[*]$dbh->disconnect();
  

  数据库中的图
  


[*]+--------------------+-------------+------------+---------------------+
[*]| room               | in_bytes    | out_bytes| date                |
[*]+--------------------+-------------+------------+---------------------+
[*]| xxxx               | 85.9 Mb/s   | 99.5 Mb/s| 2011-11-04 10:29:49 |
[*]| xxxx               | 14.1 Mb/s   | 80.7 Mb/s| 2011-11-04 10:29:49 |
[*]| xxxx               | 190.3 Mb/s| 332.6 Mb/s | 2011-11-04 10:29:49 |
[*]| xxxx               | 8968.4 kb/s | 119.9 Mb/s | 2011-11-04 10:29:49 |
[*]| xxxx               | 384.0 b/s   | 576.0 b/s| 2011-11-04 10:29:49 |
[*]+--------------------+-------------+------------+---------------------+
  

  本文出自 “BSDerの-专注于开源领域” 博客,请务必保留此出处http://hellosa.blog.51cto.com/2698675/705854


页: [1]
查看完整版本: perl 获取监控数据