为自定义事实对红宝石中的linux输出进行greping或过滤

时间:2018-07-18 23:18:08

标签: ruby linux puppet facter

我是红宝石的初学者,我一直为此感到惊讶: 我需要“将ethtool输出拆分为不同的变量,

这就是我所做的:

$(document).ready( function() {
  var buttons = $('button');

  for( var i = 0; i < buttons.length; ++i ) {
    buttons.eq(i).click(
        // ONLY EDIT THE CODE BELOW THIS LINE
        function() {
            $('ul').append('<li>' + i + '</li>')
        }
        // ONLY EDIT THE CODE ABOVE THIS LINE
    );
  }
});

这是输出(仅用于一个接口):

[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

我只需要驱动程序和固件信息,我已经尝试将带有“或”的grep添加到命令执行中,如下所示:

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

但是它不起作用,它会打印一个空行。

最后,我想做的事情是这样的:

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

您能给我提示如何继续吗?

在此先感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

String#scan在这种情况下很方便。假设您的样本数据在名为data的字符串中:

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

这将输出一个数组:

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

答案 1 :(得分:2)

ifdata = ifline
  .lines                                       # array of \n-terminated lines
  .map { |line| line.chomp.split(': ', 2) }    # array of [key, value] pairs
  .select { |line| line.length > 1 }           # get rid of anomalous "enp1s0f1d1"
  .to_h                                        # hashify

ifdata['driver']
# => sfc
ifdata['firmware-version']
# => 4.2.2.1003 rx1 tx1