我试图parsing一个dhcpd.conf文件,看起来像这样:
authoritative; subnet xxxx netmask xxxx { range xxxx xxxx; deny unknown-clients; default-lease-time 86400; max-lease-time 86400; option domain-name "bla"; option domain-name-servers xxxx; option broadcast-address xxxx; option subnet-mask xxxx; option routers xxxx; host host1 { hardware ethernet 00:e1:4c:68:00:53; fixed-address 1.1.1.1; } host host2 { hardware ethernet 01:e2:4d:69:01:54; fixed-address 2.2.2.2; } host host3 { hardware ethernet 02:e3:4e:70:02:55; fixed-address 3.3.3.3; } host host4 { hardware ethernet 03:e4:4f:71:03:56; fixed-address 4.4.4.4; } host host5 { hardware ethernet 04:e5:5f:72:04:57; fixed-address 5.5.5.5; } }
最后,我需要通过主机块(不pipe名称)来循环,并将MAC地址和IP地址分配给variables以处理组合。 到目前为止,我只devise了一个variables:
for MAC in `cat /etc/dhcp/dhcpd.conf | grep "hardware ethernet" | awk '{ print $3 }' | tr ";" " "` do echo "Found MAC address: " $MAC "Found IP: <I need the IP Variable here...>" done
也许最好是以某种方式“grep”主机块来循环这些,但我不知道如何做到这一点。
有谁能给我提示如何做到这一点?
谢谢
鉴于输入文件格式正确(MAC后接IP),接下来的sed
一个班轮将列出“MAC,IP”csv对。 你可以解析它,做任何你想要的。
sed -n '/\s*hardware ethernet/{s/\s*hardware ethernet \(.*\);/\1/;N;s/\([a-z0-9:]*\)\s*fixed-address \(.*\);/\1,\2/p}' /etc/dhcp/dhcpd.conf
输出:
00:e1:4c:68:00:53,1.1.1.1 01:e2:4d:69:01:54,2.2.2.2 02:e3:4e:70:02:55,3.3.3.3 03:e4:4f:71:03:56,4.4.4.4 04:e5:5f:72:04:57,5.5.5.5
为了生成你的例子中的确切输出,
sed -n '/\s*hardware ethernet/{s/\s*hardware ethernet \(.*\);/\1/;N;s/\([a-z0-9:]*\)\s*fixed-address \(.*\);/Found MAC address: \1, Found IP: \2/p}' /etc/dhcp/dhcpd.conf
输出:
Found MAC address: 00:e1:4c:68:00:53, Found IP: 1.1.1.1 Found MAC address: 01:e2:4d:69:01:54, Found IP: 2.2.2.2 Found MAC address: 02:e3:4e:70:02:55, Found IP: 3.3.3.3 Found MAC address: 03:e4:4f:71:03:56, Found IP: 4.4.4.4 Found MAC address: 04:e5:5f:72:04:57, Found IP: 5.5.5.5
编辑
您可以从每一对中提取MAC和IP,并按如下方式使用它们。
for v in $(sed -n '/\s*hardware ethernet/{s/\s*hardware ethernet \(.*\);/\1/;N;s/\([a-z0-9:]*\)\s*fixed-address \(.*\);/\1,\2/p}' /etc/dhcp/dhcpd.conf); do mac="${v%,*}" ip="${v#*,}" echo "MAC: $mac" echo "IP: $ip" done