Created
February 28, 2016 03:33
-
-
Save penguinpowernz/2827f7635f64327048a7 to your computer and use it in GitHub Desktop.
Ruby network interface information parser
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
require 'json' | |
ifaces = [] | |
whitelist = [ "eth", "wlan", "en" ] | |
names = `ip link sh`.scan(/^\d+: (.*):/).flatten.select do |name| | |
whitelist.any? {|pattern| name.start_with?(pattern) } | |
end | |
names.each do |name| | |
iface = { | |
interface: name, | |
ip: nil, | |
gateway: nil, | |
routed: false, | |
enabled: false | |
} | |
# get the ip address out | |
ip = `ip addr sh #{name} 2>/dev/null` | |
next unless $?.success? | |
addrs = ip.lines.grep(/inet /) # we are looking for a line like this: inet 10.0.60.91/32 scope global enp6s0 | |
next if addrs.empty? | |
iface[:ip] = addrs.first.split(" ")[1] | |
# get the route | |
routes = `ip route`.lines.grep(/#{name}/) | |
if routes.first.start_with?("default") | |
iface[:gateway] = routes.first.split(" ")[2] # first line always has default: default via 192.168.1.1 dev eth0 metric 1024 | |
iface[:routed] = true # if this interface is on the first line, all traffic is routed through it | |
else | |
iface[:routed] = false | |
routes.each do |r| | |
next if r.include?("proto kernel") # ones with this line seem to be network routes: 192.168.1.0/24 dev eth0 proto kernel scope link src 192.168.1.77 | |
iface[:gateway] = r.split(" ").first # the first without proto kernel should show the actual gateway: 192.168.1.1 dev eth0 scope link metric 1024 | |
break # we only care about the first one | |
end | |
end | |
# get the link state | |
link = `ip link sh #{name}` | |
if $?.success? | |
link = link.lines.first | |
linkup = link.split(" ")[2].include?(",UP") # this is the part: <BROADCAST,MULTICAST,UP,LOWER_UP> | |
stateup = link.include?("state UP") # this just searches the first line | |
iface[:enabled] = linkup && stateup | |
end | |
# pull the DNS namservers | |
iface[:dns1], iface[:dns2] = *File.read('/etc/resolv.conf').lines.grep(/^nameserver \d+\./)[0..1].map {|l| l.split(" ")[1].strip } | |
ifaces << iface | |
end | |
puts JSON.pretty_generate(ifaces) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment