Skip to content

Instantly share code, notes, and snippets.

@cthiel
Created September 23, 2011 09:40
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cthiel/1237041 to your computer and use it in GitHub Desktop.
Save cthiel/1237041 to your computer and use it in GitHub Desktop.
Parser for Amazon EC2 Public IP Range Announcements
#!/usr/bin/env ruby
# Parser for Amazon EC2 Public IP Range Announcements
# Author: Christoph Thiel <cthiel@suse.com>
# Date: 2011-09-23
require 'rubygems'
require 'bundler/setup'
require 'nokogiri'
require 'open-uri'
require 'netaddr'
regexp = /(US East|US West|EU|Singapore|Tokyo)|(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\/\d{1,2})/
if ARGV.first.nil?
puts "Usage:\n ./ec2-ip-ranger.rb https://forums.aws.amazon.com/ann.jspa?annID=1182"
exit 1
end
url = ARGV.first
page = Nokogiri::HTML(open(url))
debug = ARGV.last.eql?('-d')
region_map = { 'US East' => 'us-east-1',
'US West' => 'us-west-1',
'EU' => 'eu-west-1',
'Singapore' => 'ap-southeast-1',
'Tokyo' => 'ap-northeast-1'
}
ip_map = {}
size_map = {}
current_region = ''
page.css(".jive-body").text.strip.gsub(/\\n/,' ').scan(regexp) do |match|
if match[1].nil?
if !current_region.empty? and debug
puts region_map[current_region] + ": " + size_map[region_map[current_region]].to_s + " hosts"
end
current_region = match[0]
ip_map.merge!({region_map[current_region] => []})
size_map.merge!({region_map[current_region] => 0})
elsif match[0].nil?
ip_map[region_map[current_region]] << match[1]
size_map[region_map[current_region]] += NetAddr::CIDR.create(match[1]).size
puts region_map[current_region] + ": " + match[1] if debug
end
end
puts region_map[current_region] + ": " + size_map[region_map[current_region]].to_s + " hosts" if debug
unless debug
ip_map.each do |region, ips|
puts "[#{region}]"
sorted_ips = ips.sort_by{|i| i.split('.').first.to_i }.join(' ')
puts "public-ips=\"#{sorted_ips}\""
end
end
source :rubygems
gem 'nokogiri'
gem 'netaddr'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment