Skip to content

Instantly share code, notes, and snippets.

@chrp
Created June 12, 2015 20:43
Show Gist options
  • Save chrp/50858dc350682345153a to your computer and use it in GitHub Desktop.
Save chrp/50858dc350682345153a to your computer and use it in GitHub Desktop.
Wraps the output of ```netstat -I en0 -b``` to keep an eye on your bandwith use.
#!/usr/bin/env ruby
#ln -s $PWD/ifwatch /usr/local/bin/
LIMITS = {
red: 30*1024**2,
yellow: 20*1024**2,
green: 0
}
def humanize_bytes bytes, units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']
bytes < 1024 ? "#{sprintf('%9.2f', bytes)} #{units.first}" : humanize_bytes(bytes/1024.0, units[1..-1])
end
def colorize str, color
color_code = {default: 0, red: 31, green: 32, yellow: 33, blue: 34, pink: 35, gray: 37}[color]
"\e[#{color_code}m#{str}\e[0m"
end
begin
while 1
# retrieve current io use from netstat
lines = `netstat -I en0 -b`.split("\n")
fields = lines[1].split(' ').compact
bytes = [Integer(fields[6]), Integer(fields[9])]
bytes << bytes.inject(0) { |mem,val| mem + val }
# get & save base for today
filename ||= "#{File.expand_path(File.dirname(__FILE__))}/#{Time.now.strftime('%y%m%d_base')}"
base_bytes ||= if File.exist?(filename)
File.read(filename).split(';').map(&:to_i)
else
File.write(filename, bytes.map(&:to_s).join(';'))
bytes
end
#clear screen
print "\e[H\e[2J"
%w(in out total).each_with_index do |s, i|
current = bytes[i] - base_bytes[i]
color = Array(LIMITS.find { |k,v| current > v }).first if s == 'total'
color ||= :gray
puts "#{s}:#{' '*(6-s.length)} #{colorize(humanize_bytes(current), color)}"
end
sleep(1)
end
rescue SystemExit, Interrupt
puts ""
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment