Created
February 27, 2012 13:13
-
-
Save Eising/1923695 to your computer and use it in GitHub Desktop.
Script to find IPs that belong in a list of subnets
This file contains 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 'ipaddr' | |
def usage | |
puts "#{$0} supernets file" | |
puts "Checks if a file full of ip-addresses is part of a supernet \n\n" | |
puts "Supernets: A comma-separated list of CIDR-noted networks. NO SPACES!\n\n" | |
puts "Example:" | |
puts "#{$0} 10.0.0.0/8,172.16.0.0/12 badguys.txt" | |
Process.exit | |
end | |
ARGV.count == 2 or usage | |
(rawips, filename) = ARGV | |
unless rawips =~ /^[0-9\.,\/]+$/ | |
puts "Illegal value of supernets" | |
usage | |
end | |
myrawranges = rawips.split(',') | |
firstoctets = myrawranges.collect { |x| x.match(/^(\d+)\./)[1] rescue nil } # extract first octet | |
begin | |
fh = File.new(filename) | |
rescue => e | |
puts "Couldn't open file #{filename} - #{e}" | |
usage | |
Process.exit | |
end | |
myranges = Array.new | |
myrawranges.each do |addr| | |
myranges << IPAddr.new(addr, Socket::AF_INET) | |
end | |
ips = Array.new # Initialize the array of IPs gathered from file | |
fh.each_line do |line| | |
firstoctets.each do |oct| | |
if line =~ /^#{oct}\./ # only add IPs that actually match on the first octet. | |
ips << line.chomp | |
end | |
end | |
end | |
ips.each do |ip| | |
myranges.each do |range| | |
begin | |
o_ip = IPAddr.new("#{ip}/32", Socket::AF_INET) | |
rescue | |
# just skip entries that are not real ip addresses | |
end | |
if range.include?(o_ip) | |
puts ip | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment