Last Updated: February 25, 2016
·
1.359K
· jcran

Gathering System Information with ohai

Recently found myself neck deep in ruby system calls, specifically to query information about the system i was running on. Turns out the Ohai gem (from the Opscode folks) is really handy for this. The first step is simply to create an Ohai system object:

irb(main):003:0> o = Ohai::System.new
=> #

Then, load plugins to set up "providers" of information. Here's an example of the system information you can obtain:

irb(main):030:0> o.require_plugin "linux::cpu"
=> true
irb(main):031:0> o[:cpu]
=> {"0"=>{"vendor_id"=>"GenuineIntel", "family"=>"6", "model"=>"23", "model_name"=>"Intel(R) Core(TM)2 Duo CPU     P8600  @ 2.40GHz", "stepping"=>"10", "mhz"=>"2388.885", "cache_size"=>"3072 KB", "flags"=>["fpu", "vme", "de", "pse", "tsc", "msr", "pae", "mce", "cx8", "apic", "sep", "mtrr", "pge", "mca", "cmov", "pat", "pse36", "clflush", "dts", "acpi", "mmx", "fxsr", "sse", "sse2", "ss", "syscall", "nx", "lm", "constant_tsc", "up", "arch_perfmon", "pebs", "bts", "nopl", "xtopology", "tsc_reliable", "nonstop_tsc", "aperfmperf", "pni", "ssse3", "cx16", "sse4_1", "xsave", "hypervisor", "lahf_lm", "dtherm"]}, "total"=>1, "real"=>0}

irb(main):032:0> o.require_plugin "linux::lsb"
=> true
irb(main):033:0> o[:lsb]
=> {"id"=>"Ubuntu", "release"=>"12.04", "codename"=>"precise", "description"=>"Ubuntu 12.04.1 LTS"}

And here's an example of gathering network information

irb(main):023:0> o.require_plugin "network"
irb(main):024:0> o.require_plugin "linux::network"
=> true
irb(main):027:0> o['network']['interfaces']['lo']
=> {"mtu"=>"16436", "flags"=>["LOOPBACK", "UP", "LOWER_UP"], "encapsulation"=>"Loopback", 
"addresses"=>{"127.0.0.1"=>{"family"=>"inet", "prefixlen"=>"8", "netmask"=>"255.0.0.0", "scope"=>"Node"}, "::1"=>{"family"=>"inet6", "prefixlen"=>"128", "scope"=>"Node"}}, "state"=>"unknown"}
irb(main):028:0> 
irb(main):029:0> o['network']['interfaces'].each { |key,val| puts key } 
lo
eth0

If you're interested in this sort of thing, i'd encourage you to check out the ohai specs (https://github.com/opscode/ohai/tree/master/spec/ohai/plugins) which appear to be the main form of usage documentation.