Skip to content

Instantly share code, notes, and snippets.

@andruby
Created April 17, 2010 11:01
Show Gist options
  • Save andruby/369469 to your computer and use it in GitHub Desktop.
Save andruby/369469 to your computer and use it in GitHub Desktop.
Zerigo dynamic dns updater
#!/usr/bin/env ruby
# Dynamic DNS updater by Andruby for Zerigo
# www.andrewsblog.org
ApiKey = 'myzerigoapikey' # your Zerigo API key
Host = 'test.example.com' # the host you want to dynamically update
User = '[email protected]' # your Zerigo username
NameServer = 'a.ns.zerigo.net' # Zerigo nameserver to query
LastIpTmpFile = '/tmp/dyn_update_last_ip' # a temporary file where we store the last ip adress
# Load libraries
require 'open-uri'
require 'ipaddr'
def with_rescue(msg, &block)
yield
rescue Exception => e
puts "Error while #{msg}"
p e
end
def ip_changed?(current_ip)
previous_ip = (IPAddr.new(File.read(LastIpTmpFile)) rescue nil)
File.open(LastIpTmpFile,'w') { |f| f.print current_ip.to_s }
previous_ip != current_ip
end
real_ip = with_rescue("getting current ip") do
body = open('http://checkip.dyndns.org').read
IPAddr.new(body.match(/\d+\.\d+\.\d+\.\d+/).to_s)
end
puts "Real ip: #{real_ip}"
# Check if our ip changed since last time.
# This saves us from querying the Zerigo DNS server.
unless ip_changed?(real_ip)
puts "IP Adress is still the same, not updating"
exit
end
# Load more libraries
require 'resolv'
require 'rubygems'
require 'net/dns/resolver'
# Resolving the IP address stored in the DNS server
# This could be refactored to be cleaner
dns_ip = with_rescue("resolving DNS ip") do
ns_ip = Resolv.getaddress(NameServer).to_s
# make sure you query the right Nameserver
res = Net::DNS::Resolver.new(:nameservers => ns_ip)
last_ip = nil
res.search(Host).each_address { |ip| last_ip = ip }
last_ip
end
puts "DNS ip: #{dns_ip}"
if real_ip == dns_ip
puts "Real IP matches DNS IP (#{real_ip}), doing nothing"
else
url = "http://update.zerigo.com/dynamic?host=#{Host}&user=#{User}&password=#{ApiKey}"
print "Setting new IP address: "
puts open(url).read
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment