Sunday, August 05, 2007

BWM-NG + Ruby for Gathering Network Stats

BWM-NG is a great tool for getting real time stats, but by using the CSV output you can capture historical data as well.

# bwm-ng -o csv -t 2500 -c 1 -C,
1186367009,em2,198.09,50.12,248.21,126,498,0.40,0.80,1.19,2,1,0.00,0.00,0,0
1186367009,lo0,0.00,0.00,0.00,0,0,0.00,0.00,0.00,0,0,0.00,0.00,0,0
1186367009,total,198.09,50.12,248.21,126,498,0.40,0.80,1.19,2,1,0.00,0.00,0,0

So to make use of this, we'll need some sort of Time/Date API to convert the etime into something useful as well as the CSV parser.

#!/usr/bin/env ruby
require 'csv'
require 'pp'
require 'date'

bytes={}
packets={}
errors={}
cmd = 'bwm-ng -o csv -t 2500 -c 1 -C,'
p = IO.popen(cmd) do |f|
f.each_line do |g|
h = CSV::parse(g).flatten
$dtg = Time.at(h[0].to_i).to_s
interface = h[1]
bytes[interface] = h[2..4]
packets[interface] = h[7..9]
errors[interface] = h[14..15]
end
end

puts "Date: #{$dtg}"
bytes.keys.sort.each do |i|
puts "\nInterface: #{i} (TX/RX/Total)"
print "Bytes:"
pp bytes[i]
print "Packets:"
pp packets[i]
print "Errors:"
pp errors[i]
end


And the output looks like

# ./rbbw.rb
Date: Mon Aug 06 03:35:17 +0000 2007

Interface: em2 (TX/RX/Total)
Bytes:["128.88", "76.37", "205.25"]
Packets:["0.80", "1.19", "1.99"]
Errors:["0", "0"]

Interface: lo0 (TX/RX/Total)
Bytes:["133.65", "133.65", "267.30"]
Packets:["1.59", "1.59", "3.18"]
Errors:["0", "0"]

Interface: total (TX/RX/Total)
Bytes:["262.53", "210.02", "472.55"]
Packets:["2.39", "2.78", "5.17"]
Errors:["0", "0"]


Where these are obviously rate values (per second) for a very boring FreeBSD VM.

No comments: