-
-
Save pol/184671 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'open-uri' | |
require 'rubygems' | |
require 'json' | |
# Change these settings | |
hostname = 'home.hostname.com' # the hostname you use to connect to home ip | |
apikey = 'your-dreamhost-api-key' # a dreamhost api key that has access to all dns functions | |
# method to generate a unique_id | |
# TODO: use uuid instead | |
def unique_id | |
Time.new.to_f.to_s | |
end | |
# method to generate api url | |
def open_url(opts = {}) | |
u = "https://api.dreamhost.com/?" + | |
"key=#{opts[:key]}&" + | |
"cmd=#{opts[:cmd]}&" + | |
"unique_id=#{unique_id}" | |
u += "&format=#{opts[:format]}" if opts[:format] | |
u += "&type=a&value=#{opts[:value]}" if opts[:value] | |
u += "&record=#{opts[:record]}" if opts[:record] | |
open(u, 'UserAgent' => 'RubyWget').read | |
end | |
# retrieve current ip | |
ip = open('http://checkip.dyndns.com'){ |f| /([1-9]{1,3}\.){3}[0-9]{1,3}/.match(f.read)[0].to_a[0] } | |
puts "Current external ip: #{ip}" | |
# fetch the dreamhost's stored ip | |
dns = open_url({:key => key, | |
:cmd => "dns-list_records", | |
:format => 'json'}) | |
storedIP = JSON.parse(dns).select{|d| d['record'] == hostname }.first['value'] | |
puts "Stored ip from dreamhost for #{hostname}: #{storedIP}" | |
# update the dreamhost ip if it has changed | |
if ip == storedIP | |
puts 'IP addresses match. No need to DNS' | |
else | |
puts "IP addresses do not match, changing dreamhost ip for #{hostname} from #{storedIP} to #{ip}." | |
dns = open_url({:key => apikey, | |
:cmd => 'dns-remove_record', | |
:record => hostname, | |
:value => storedIP}) | |
puts "Removed current DNS entry: #{dns}" | |
dns = open_url({:key => apikey, | |
:cmd => 'dns-add_record', | |
:record => hostname, | |
:value => ip}) | |
puts "Added new DNS entry: #{dns}" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment