ifconfig.rb

i wanted to collect some live data from my machine this afternoon, so i wrote this. grabs ifconfig data for eth0, parses out RX packets, TX packets, and generates a string containing csv data.

class Ifconfig
  RX_REGEX = /^\s+RX packets:(\d+)/
  TX_REGEX = /^\s+TX packets:(\d+)/
  COLLISIONS_REGEX = /^\s+collisions:(\d+)/

  def collect samples = 120
    collected = []
    samples.times do
      collected < < row.join(',')
      sleep 1
    end
    header_row.join(',') + "\n" + collected.join("\n")
  end

  private
    def header_row
      ['date', 'rx packets', 'tx packets', 'collisions']
    end

    def row device = 'eth0'
      output = `/sbin/ifconfig #{device}`
      rx = output.match(RX_REGEX)[1]
      tx = output.match(TX_REGEX)[1]
      collisions = output.match(COLLISIONS_REGEX)[1]
      [Time.now.strftime('%Y-%m-%d %H:%M'), rx, tx, collisions]
    end
end

use it like this:

# collect data
require 'ifconfig'
ifconfig = Ifconfig.new
data = ifconfig.collect # get a drink while you wait

# stuff it into swivel
require 'swivel'
swivel = Swivel::Connection.new
data_set = swivel.upload :name => 'spork: ifconfig eth0', :data => data

# create a graph of RX packets over time in swivel
graph = swivel.create_graph :x_axis_column => data_set.data_columns[0].id,
  :columns => data_set.data_columns[1].id, :graph_type => 'LineGraph'
graph.save!

NOTE: wordpress kills my backslash-n newline characters. but you know, they’re there. copy/paste diligently.


About this entry