Skip to content

Instantly share code, notes, and snippets.

@pete
Created February 11, 2009 00:21
Show Gist options
  • Save pete/61715 to your computer and use it in GitHub Desktop.
Save pete/61715 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require 'socket'
localhost = Socket.gethostbyname(Socket.gethostname).first
npackets = ARGV[0] ? ARGV[0].to_i : 1_000
def top_n(name, data)
data.map { |h,stats|
[h, stats[name]]
}.sort_by { |h,n|
-n
}.reject { |h,n| n.zero? }.map { |h,n|
"\t%10.02fk : %s" % [n.to_f / 1024, h]
}
end
($stderr << "Waiting for #{npackets} packets...").flush
raw_data = IO.popen("sudo tcpdump -tt -c #{npackets} 2>/dev/null").readlines
$stderr.puts "Done"
hosts = raw_data.map { |l|
l.chomp!
a = l.split(/ /)
timestamp, wtf1, src, wtf2, dst, * = a
size = a.last.to_i
{ :src => src, :dst => dst.sub(/:$/, ''), :size => size }
}.inject(Hash.new { |x,y| x[y] = {:up => 0, :down => 0} }) { |h,a|
next(h) if a[:size].zero?
if a[:src].start_with?(localhost)
h[a[:dst]][:up] += a[:size]
elsif a[:dst].start_with?(localhost)
h[a[:src]][:down] += a[:size]
end
h
}
ups = top_n(:up, hosts)
downs = top_n(:down, hosts)
puts "Uploading:", *ups
puts "Downloading:", *downs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment