Created
February 11, 2022 21:20
-
-
Save ryangreenberg/646cfdd584425eee137e2936ce9ad29b to your computer and use it in GitHub Desktop.
Check IP addresses against AWS's published ip ranges
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' | |
require 'json' | |
require 'open-uri' | |
# From https://docs.aws.amazon.com/general/latest/gr/aws-ip-ranges.html#aws-ip-download | |
source_url = 'https://ip-ranges.amazonaws.com/ip-ranges.json' | |
file = File.join(__dir__, 'ip-ranges.json') | |
unless File.exists?(file) | |
warn "Downloading from #{source_url} to #{file}..." | |
URI.open(source_url) { |data| File.write(file, data.read) } | |
end | |
json = File.read('ip-ranges.json') | |
data = JSON.parse(json)['prefixes'] | |
data_by_prefix = data.map do |d| | |
[IPAddr.new(d['ip_prefix']), d] | |
end.to_h | |
if ARGV.empty? | |
while true | |
print "Enter IP address: " | |
input = STDIN.gets.strip | |
addr = IPAddr.new(input) | |
data = data_by_prefix.detect {|prefix, data| prefix.include?(addr) }[1] | |
puts data | |
end | |
else | |
ARGV.each do |input| | |
puts input | |
addr = IPAddr.new(input) | |
data = data_by_prefix.detect {|prefix, data| prefix.include?(addr) }[1] | |
puts data | |
puts | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment