nslookup.rb
1 2 #!/usr/bin/env ruby 3 4 LOOKUP_URL = 'http://toolbar.netcraft.com/site_report?url=%s' 5 MATCH_RE = /<td><b>IP address<\/b><\/td><td.*?>([\d\.]+)<\/td>/ 6 HOSTS_FILE_PATH = '/etc/hosts' 7 8 require 'open-uri' 9 10 host = ARGV.select { |arg| arg !~ /^\-/ }.first 11 update_hosts_file = ARGV.select { |arg| arg == '--hosts' }.any? 12 13 if open(LOOKUP_URL % host).read =~ MATCH_RE 14 ip = $1 15 puts ip 16 if update_hosts_file 17 File.open(HOSTS_FILE_PATH, 'a') do |file| 18 file.write("\n#{ip} #{host}") 19 end 20 end 21 else 22 puts 'There was an error looking up this host.' 23 end
Usage:
1 2 ./nslookup.rb youtube.com
To add the entry to your hosts file:
1 2 sudo ./nslookup.rb youtube.com --hosts