我是ruby的初学者,我一直在为这个而头疼:我需要"将ethtool输出拆分为不同的变量,
这就是我所做的:
[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
这是输出(仅用于一个接口(:
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
我只需要驱动程序和fimware信息,我已经尝试将带有"or"的grep添加到命令执行中,如下所示:
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
但它不起作用,它打印了一条空行。
最后,我想做的是:
[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
你能给我一个如何继续的提示吗?
提前感谢您的帮助!
String#扫描在这种情况下很方便。假设您的样本数据在一个名为data:的字符串中
data.scan(/(firmware-version: |driver: )(.+)/)
这会输出一个数组:
=> [["driver: ", "sfc"], ["firmware-version: ", "4.2.2.1003 rx1 tx1"]]
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