0 Replies - 1298 Views - Last Post: 28 February 2010 - 07:42 PM

#1 dorknexus   User is offline

  • or something bad...real bad.
  • member icon

Reputation: 1272
  • View blog
  • Posts: 4,625
  • Joined: 02-May 04

Bandwidth Usage in Linux

Posted 28 February 2010 - 07:42 PM

Description: Simply invoke this script using the ruby interpreter, passing in the name of the interface as the only argument: ruby bw.rb eth0A quick Ruby script to print out some basic transfer usage of a given interface in Linux (and most popular UNIX-like kernels).
# Script to display the transfer information of a given
# interface.  Relies on /proc/net/dev for byte totals.

require 'fileutils'

if ARGV.length < 1
	puts "Usage: #{$0} <interface>"
	exit -1
end

found_iface = false
iface = ARGV[0]
net_info = File.new('/proc/net/dev', 'r')
SI_STR = ['Bytes', 'KB', 'MB', 'GB']

# Convert transfer amounts from raw bytes to something more readable
def humanize(transfer)
	si = 0
	while transfer >= (2 ** 10) and si < SI_STR.length
		transfer /= (2 ** 10).to_f
		si += 1
	end

	sprintf('%.2f %s', transfer, SI_STR[si])
end

while line = net_info.gets
	# Find the proper interface line
	if line =~ /#{iface}/
		found_iface = true
		# Remove the interface prefix (i.e. "eth0:")
		line.sub!(/^s*#{iface}:/, '')
		# Split the numbers into an array
		line = line.split(/s+/)
		# Extract the number of bytes rx'd and tx'd
		rx, tx = line[0].to_i, line[8].to_i

		total = humanize(rx + tx)
		rx = humanize(rx)
		tx = humanize(tx)

		puts "#{iface} transfer:"
		puts 'Recieved: ' + rx 
		puts 'Transmitted: ' + tx
		puts 'Total: ' + total
	end
end

if not found_iface
	puts "Unable to find interface: #{iface}"
	exit -1
end

##



Is This A Good Question/Topic? 0
  • +

Page 1 of 1