ホーム » 「speedtest-cli」タグがついた投稿
タグアーカイブ: speedtest-cli
speedtest-cliとrrdtool
インターネットとの通信速度を計測する speedtest-cli で Linux の上で測定できそうなので、毎日測定するようにしてみた。MRTG を単純に使うと5分おきになってしまうので、rrdtool を使って1日1回更新にてデータを生成させる。
#!/usr/bin/perl my $pgname = "speedtest" ; my $rrdfile = "/var/lib/munin/localdomain/localhost.localdomain-$pgname.rrd" ; my $graphfile = "/var/cache/munin/www/localdomain/localhost.localdomain/$pgname.png" ; my $rrdtool = "/usr/bin/rrdtool" ; my $speedtest = "/usr/local/sbin/speedtest-cli" ; my $time = time() ; my $debug = 0 ; sub fetchvalue { my ($upv , $dwv) = @_ ; my $upload = 0 , $download = 0 ; open( FH , "$speedtest |" ) or die( "Can't open $speedtest." ) ; while( my $line = ) { if ( $line =~ /^Upload:\s*([\d\.]+)\s*(M|K|)bit\/s/i ) { $upload = $1 ; $upload *= 1000000 if ( $2 eq "M" ) ; $upload *= 1000 if ( $2 eq "K" || $2 eq "k" ) ; } if ( $line =~ /^Download:\s*([\d\.]+)\s*(M|K|)bit\/s/i ) { $download = $1 ; $download *= 1000000 if ( $2 eq "M" ) ; $download *= 1000 if ( $2 eq "K" || $2 eq "k" ) ; } } close( FH ) ; $$upv = $upload ; $$dwv = $download ; } sub create { my $cmd = "$rrdtool create $rrdfile" ." --step 86400" ." DS:upload:GAUGE:200000:0:U" ." DS:download:GAUGE:200000:0:U" ." RRA:LAST:0.5:1:7" ." RRA:AVERAGE:0.5:3:7" ." RRA:MIN:0.5:3:7" ." RRA:MAX:0.5:3:7" ; print $cmd."\n" if ( $debug ) ; system( $cmd ) ; } sub update { # rrdファイルが無ければ作る create() unless( -f $rrdfile ) ; # 値を取得して更新 my $upv , $dwv ; fetchvalue( \$upv , \$dwv ) ; my $cmd = "$rrdtool update $rrdfile" ." N:$upv:$dwv" ; print $cmd."\n" if ( $debug ) ; system( $cmd ) ; } sub graph { my $start = $time - 3600*24*200 ; my $cmd = "$rrdtool graph $graphfile" ." --imgformat PNG" ." --start $start" ." --end $time" ." --title \"SpeedTest\"" ." --height 150" ." --font DEFAULT:7:Consolas" ." --vertical-label \"bit/sec\"" ." --color FRAME#f3f3f3" ." --color AXIS#F3F3F3" ." --color SHADEA#f3f3f3" ." --color SHADEB#f3f3f3" ." --color ARROW#f3f3f3" ." COMMENT:\" cur avg min max\\n\"" ." DEF:upload=$rrdfile:upload:LAST" ." LINE:upload#00FF00:\"Upload \"" ." GPRINT:upload:LAST:\"%6.2lf%s /\"" ." GPRINT:upload:AVERAGE:\"%6.2lf%s /\"" ." GPRINT:upload:MIN:\"%6.2lf%s /\"" ." GPRINT:upload:MAX:\"%6.2lf%s \\n\"" ." DEF:download=$rrdfile:download:LAST" ." CDEF:download_minus=download,-1,*" ." LINE:download_minus#0000FF:\"Download\"" ." GPRINT:download:LAST:\"%6.2lf%s /\"" ." GPRINT:download:AVERAGE:\"%6.2lf%s /\"" ." GPRINT:download:MIN:\"%6.2lf%s /\"" ." GPRINT:download:MAX:\"%6.2lf%s \\n\"" ." > /dev/null" ; print $cmd."\n" if ( $debug ) ; system( $cmd ) ; } if ( @ARGV > 0 && $ARGV[0] eq "config" ) { create() ; } elsif ( @ARGV > 0 && $ARGV[0] eq "update" ) { update() ; } elsif ( @ARGV > 0 && $ARGV[0] eq "graph" ) { graph() ; } else { update() ; graph() ; }