Created
April 23, 2012 14:26
-
-
Save granolocks/2471244 to your computer and use it in GitHub Desktop.
Simple Ifconfig Parser in Ruby
This file contains 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
class IfconfigParser | |
MAC_REGEX = /^(\S{1,2}:\S{1,2}:\S{1,2}:\S{1,2}:\S{1,2}:\S{1,2})?$/ | |
# NOTE: this has some slightly weird results for wlan interfaces. Really meant to be used for eth0 | |
def self.ifconfig(iface) | |
output = Hash.new | |
ifconfig_string = `ifconfig #{ iface }` | |
ifconfig_string.gsub!("RX ", "RX_") | |
ifconfig_string.gsub!("TX ", "TX_") | |
ifconfig_string.gsub!(" (", "_(") | |
raw_array = ifconfig_string.split(' ').grep(/:/) | |
output["HWaddr"] = raw_array.grep(MAC_REGEX)[0] | |
output["ipv6_addr"] = ifconfig_string.split("\n").grep(/inet6/)[0] | |
output["ipv6_addr"] = output["ipv6_addr"].split[2] unless output["ipv6_addr"] == nil | |
hash_array = raw_array.map {|e| e.split(':') } | |
hash_array.reject!{|e| e.length != 2 } | |
hash_array.inject(output) do |output, element| | |
output[element[0]] = element[1] | |
output | |
end | |
output | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment