Instantly share code, notes, and snippets.

Embed
What would you like to do?
Small script to parse nginx access log file, and find out from what organisation (AS) was visiting your website
#!/usr/bin/env ruby
require 'teamcymru'
require 'ipaddr'
c = TeamCymru::ASNClient.new
ips = Array.new
ARGF.each do |line|
ip = IPAddr.new(line.split()[0])
# rewrite ::ffff:v4inv6-notation to native v4
ips << ip.native.to_s
end
# group and count IPs
grouped_ips = ips.inject(Hash.new(0)) { |h, ip| h[ip] += 1; h}
grouped_ips.sort_by{|k,v| v}.reverse.each do |ip, num|
as_info = c.lookup(ip)
printf "%5.d%55.50s %s\n", num, as_info.org, ip
end
puts "-"*80
printf "%5.d\n", ips.length
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment