rubylinuxpuppetfacter

greping or filtering linux output in ruby for custom fact


I'm a beginner in ruby and I have been blowing out my head with this: I need to "split the ethtool output into different variables,

this is what I have done:

[root@aptpka02 facter]# cat test.rb
interface = "enp8s0,enp9s0,enp1s0f0,enp1s0f1d1"
interface.split(',').each do |int|
 # call ethtool to get the driver for this NIC
  puts int
  ifline = %x{/sbin/ethtool -i #{int} 2>/dev/null }
  puts ifline

end

and this is the output (just for one interface):

enp1s0f1d1
driver: sfc
version: 4.0
firmware-version: 4.2.2.1003 rx1 tx1
bus-info: 0000:01:00.1
supports-statistics: yes
supports-test: yes
supports-eeprom-access: no
supports-register-dump: yes
supports-priv-flags: no

I just need the driver and fimware information, i've try to add the grep with "or" to the command execution like this:

interface.split(',').each do |int|
# call ethtool to get the driver for this NIC
puts int
ifline = %x{/sbin/ethtool -i #{int} 2>/dev/null | grep "driver\| firmware"}
puts ifline

end

but it doesn't work, it prints an empty line.

at the end, what I want to do is something like:

[root@aptpka02 facter]# vim test.rb
interface = "enp8s0,enp9s0,enp1s0f0,enp1s0f1d1"
interface.split(',').each do |int|
 # call ethtool to get the driver for this NIC
puts int
ifline = %x{/sbin/ethtool -i #{int} 2>/dev/null | grep "driver\| firmware"}.lines.each do | nicinfo|
 if (nicinfo = driver)
   driver = %x{/sbin/ethtool -i #{int} 2>/dev/null | grep 'driver: '}.chomp.sub("driver: ", "")
 else
  .
  .
  .
 endif

end

can you give please give me a hint in how to continue?

Thanks in advance for your help!


Solution

  • String#scan is handy for this situation. Say your sample data is in a string called data:

    data.scan(/(firmware-version: |driver: )(.+)/)
    

    this outputs an array:

    => [["driver: ", "sfc"], ["firmware-version: ", "4.2.2.1003 rx1 tx1"]]