Created
August 21, 2012 18:12
-
-
Save oogali/3418024 to your computer and use it in GitHub Desktop.
No, I don't want to install MRTG, RTG, RRDTool, MySQL, Cacti, Observium, PHP, Apache, Nginx, or FastCGI to get one-shot interface statistics.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
require 'rubygems' | |
require 'snmp' | |
require 'time' | |
def mbps(bytes, duration) | |
((bytes / duration) * 8.to_f) / 1000000 | |
end | |
def pct(bytes, speed, duration) | |
return 0 if speed == 0 | |
((100 * (bytes.to_f / duration) * 8.to_f) / speed.to_f).to_i | |
end | |
def get_bw(d, i) | |
duration = d[i][:ts].to_f - d[i - 1][:ts].to_f | |
inbytes = (d[i][:in] - d[i - 1][:in]).abs | |
outbytes = (d[i][:out] - d[i - 1][:out]).abs | |
speed = d[i][:speed] | |
"in: #{'%.2fMbps' % mbps(inbytes, duration)} (#{pct(inbytes, speed, duration)}%),\tout: #{'%.2fMbps' % mbps(outbytes, duration)} (#{pct(outbytes, speed, duration)}%)" | |
end | |
unless ARGV.length >= 2 | |
puts "#{__FILE__} <device> <community> [# of polls, default: 5] [# of seconds to sleep between polls, default: 1]" | |
exit 1 | |
end | |
dev = { | |
:host => ARGV[0], | |
:community => ARGV[1] | |
} | |
enough = false | |
poll = {} | |
polls = ARGV[2].to_i | |
polls = 5 if polls < 2 | |
delay = ARGV[3].to_i || 1 | |
delay = 1 if delay < 1 | |
polls.times do | |
SNMP::Manager.open(:Host => dev[:host], :Version => :SNMPv2c, :Community => dev[:community]) do |mgr| | |
mgr.walk([ 'ifIndex', 'ifDescr', 'ifSpeed', 'ifHCInOctets', 'ifHCOutOctets' ]) do |row| | |
idx, name, speed, inbytes, outbytes = row | |
poll[name.value] ||= [] | |
poll[name.value] << { | |
:ts => Time.now, | |
:ifindex => idx.value.to_i, | |
:interface => name.value.to_s, | |
:speed => speed.value.to_i, | |
:in => inbytes.value.to_i, | |
:out => outbytes.value.to_i | |
} | |
end | |
end | |
if enough | |
poll.keys.sort.each do |interface| | |
data = poll[interface] | |
i = data.length - 1 | |
puts "#{interface.ljust(16)}\t#{data[i][:ts]}\t\t#{get_bw(data, i)}" | |
end | |
puts | |
else | |
enough = true | |
end | |
sleep delay | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment