CCCPaste

mac_grep.rb

#!/usr/bin/env ruby

# Daniel Bowling 
# Jun 2021

require 'optparse'
require 'net/http'

api_url = URI('https://api.macvendors.com/')
cmd     = File.basename($PROGRAM_NAME)
macs    = []
options = {}
version = 0.1

OptionParser. new do |opts|
  opts.banner = "Usage: #{cmd} "

  opts.on('-v', '--version', 'Print verson') { options[:version] = true }
end.parse!

# Print version if -v specified
if options[:version]
  puts version
  exit
end

# Check for arguments
unless ARGV[0]
  puts "#{cmd}: No arguments given, try -h or --help"
  exit(64)
end

# Strip symbols from the MACs
macs = ARGV.map { |mac| mac.gsub(/[\-\.:]/, '').downcase }

# Start up the persistant connection
Net::HTTP.start(api_url.host, api_url.port, use_ssl: true) do |q|
  # Process each MAC
  macs.each do |mac|
    # API call
    res = q.request Net::HTTP::Get.new(api_url + mac)

    # Add colons to MAC if it's valid
    mac =
      if mac =~ /[0-9a-f]{12}/
        mac.gsub(/([0-9a-f]{2})/, '\1:').chomp(':')
      else
        "#{mac} ?"
      end

    # API returns a 404 if it's no good
    if res.is_a?(Net::HTTPSuccess)
      # Looks good
      puts "#{mac}\t#{res.body}"
    else
      # Uh-oh
      warn "#{mac}\t#{res.code} #{res.message}"
    end

    # API is rate-limited 1 req/sec: https://macvendors.com/api
    sleep(1)
  end
end