208_man
208_man

Reputation: 1728

How to check if DNS record exists using Ruby?

I'm trying to check whether a given host name has already been used in an A Record in our IPAM system. E.g., if https://this-internal-url.net is already "taken" in the DNS system, it should return true. Else false.

I've tried a BUNCH of different solutions, most of them from S.O.

Most of these simply err out when an invalid url is passed in:

require 'resolv'
ip_ad = Resolv.getaddress <url>
print ip_ad

simply errs out if the url doesn't exist in dns.

require 'infoblox'
# create a connection
connection = Infoblox::Connection.new(
  username: <infoblox_user>,
  password: <infoblox_passwd>,
  host: <infoblox_grid_server>,
  ssl_opts: {verify: false},
  logger: Logger.new(STDOUT)
)

search = Infoblox::Arecord.find(connection, {"name~" => "#{url}"})
print search
# also tried: search = Infoblox::Search.find(connection, "search_string~" => "#{url}")

Also:

require 'rubygems'
require 'dnsruby'
include Dnsruby
info = system("nslookup -q=txt #{url}")
print info

Also:

require 'rubygems'
require 'dnsruby'
include Dnsruby
res = Dnsruby::Resolver.new
ret = res.query(url, Types.TXT)
print "#{ret.answer}"

Also:

require 'resolv'
txt = Resolv::DNS.open do |dns|
  records = dns.getresources(url, Resolv::DNS::Resource::IN::TXT)
  records.empty? ? nil : records.map(&:data).join(" ")
end
print txt

Also:

require "resolv"
Resolv::DNS.open do |dns|
  ress = dns.getresources "infoir.com", Resolv::DNS::Resource::IN::A
  log(ress.map { |r| [r.exchange.to_s, r.preference] })
end

I know none of these snippets will evaluate to true/false. I just haven't arrived upon any solution that distinguishes between existing DNS records and non-existing records without erring out.

Upvotes: -1

Views: 773

Answers (1)

208_man
208_man

Reputation: 1728

I solved it.

name_taken = system("ping -c 1 -W 1 #{host_name}")

name_taken returns a boolean which I can use to determine whether a DNS record already exists for the given host name.

Upvotes: 0

Related Questions