Advertisement
swaggboi

mac_grep.rb

Jun 8th, 2021
1,497
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.39 KB | None | 0 0
  1. #!/usr/bin/env ruby
  2.  
  3. # Daniel Bowling <swaggboi@slackware.uk>
  4. # Jun 2021
  5.  
  6. require 'optparse'
  7. require 'net/http'
  8.  
  9. api_url = URI('https://api.macvendors.com/')
  10. cmd     = File.basename($PROGRAM_NAME)
  11. macs    = []
  12. options = {}
  13. version = 0.1
  14.  
  15. OptionParser. new do |opts|
  16.   opts.banner = "Usage: #{cmd} <MAC ADDRESS(ES)>"
  17.  
  18.   opts.on('-v', '--version', 'Print verson') { options[:version] = true }
  19. end.parse!
  20.  
  21. # Print version if -v specified
  22. if options[:version]
  23.   puts version
  24.   exit
  25. end
  26.  
  27. # Check for arguments
  28. unless ARGV[0]
  29.   puts "#{cmd}: No arguments given, try -h or --help"
  30.   exit(64)
  31. end
  32.  
  33. # Strip symbols from the MACs
  34. macs = ARGV.map { |mac| mac.gsub(/[\-\.:]/, '').downcase }
  35.  
  36. # Start up the persistant connection
  37. Net::HTTP.start(api_url.host, api_url.port, use_ssl: true) do |q|
  38.   # Process each MAC
  39.   macs.each do |mac|
  40.     # API call
  41.     res = q.request Net::HTTP::Get.new(api_url + mac)
  42.  
  43.     # Add colons to MAC if it's valid
  44.     mac =
  45.       if mac =~ /[0-9a-f]{12}/
  46.         mac.gsub(/([0-9a-f]{2})/, '\1:').chomp(':')
  47.       else
  48.         "#{mac} ?"
  49.       end
  50.  
  51.     # API returns a 404 if it's no good
  52.     if res.is_a?(Net::HTTPSuccess)
  53.       # Looks good
  54.       puts "#{mac}\t#{res.body}"
  55.     else
  56.       # Uh-oh
  57.       warn "#{mac}\t#{res.code} #{res.message}"
  58.     end
  59.  
  60.     # API is rate-limited 1 req/sec: https://macvendors.com/api
  61.     sleep(1)
  62.   end
  63. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement