Last active
February 4, 2025 10:53
-
-
Save dentarg/854aa237db1e530f1881043a3ea3d5a0 to your computer and use it in GitHub Desktop.
count_ec2_ips.rb - https://docs.aws.amazon.com/general/latest/gr/aws-ip-ranges.html
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 | |
if %w(-h --help).include?(ARGV.first) | |
abort <<~USAGE | |
#{__FILE__} <FILE> to count IPs in given file | |
#{__FILE__} to count IPs using latest file on disk | |
DL=1 #{__FILE__} to download the AWS IP ranges | |
USAGE | |
end | |
require "ipaddr" | |
require "json" | |
require "net/http" | |
ip_ranges_url = "https://ip-ranges.amazonaws.com/ip-ranges.json" | |
filename = ARGV.first | |
if ENV.key?("DL") | |
date = Time.now.strftime("%F") | |
filename = "ip-ranges_#{date}.json" | |
ip_ranges_data = Net::HTTP.get(URI(ip_ranges_url)) | |
puts "✅ Downloaded #{ip_ranges_url}" | |
File.write(filename, ip_ranges_data) | |
puts "💾 Saved them to #{filename}" | |
else | |
filename = Dir["ip-ranges_*.json"].reverse.first | |
end | |
no_file = filename.nil? || !File.exist?(filename) | |
abort "Run with DL=1 to download #{ip_ranges_url}" if no_file | |
puts "✏️ Counting IPs in #{filename}" | |
ip_ranges_data ||= File.read(filename) | |
ip_ranges = JSON.parse(ip_ranges_data) | |
count_v4 = ip_ranges["prefixes"] | |
.select { |pref| pref["service"] == "EC2" } | |
.map { |pref| 2 ** (32 - IPAddr.new(pref["ip_prefix"]).prefix) } | |
.sum | |
count_v6 = ip_ranges["ipv6_prefixes"] | |
.select { |pref| pref["service"] == "EC2" } | |
.map { |pref| 2 ** (128 - IPAddr.new(pref["ipv6_prefix"]).prefix) / 2**(128-64) }.sum | |
puts "IPv4: #{count_v4}" | |
puts "IPv6: #{count_v6}" |
Author
dentarg
commented
Feb 4, 2025
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment