The Need
When I'm away from home, I often find it rather useful to connect to my home network. Due to the dynamic IP address assigned by my Internet Service Provider, I use a third-party service to map a domain name to my dynamic address. This scenario requires that a machine in my network notifies the third-party service of network address changes; and a script to do this was fairly easy to write.
The Preparation
The first thing I need to do was create an account with a dynamic IP Domain Name Service provider. Previously I had use http://dyndns.com but their service has been intermittent for the last few days so I though a switch to http://no-ip.com was in order.
Aside from providing Dynamic DNS, No-IP provides software allowing Linux, Macintosh, and Windows computer users to easily update their dynamic address information. Even more importantly, No-IP provides an API for programmers to utilize when writing their own software to update address information.
The Script
Honestly, this could be done with a single line curl command, but that wouldn't be fun and it wouldn't help me learn Ruby. Enter The Ruby
require 'open-uri'
#set up some variables
u = "MYUSERNAME"
p = "MyPaSsWoRd"
h = "my.hostname.com"
url = "https://dynupdate.no-ip.com/nic/update?hostname=#{h}"
#open the url
f = open(url,
"User-Agent" => "Jezra's No-IP Update Script",
:http_basic_authentication => [u,p]
)
#output the return data
puts f.read()
This script is now happily running on my miniserver at 4 hour intervals.
The big take away here for me, was learning how to use open() from the open-uri module to set the User-Agent of a request as well as utilizing http basic authentication.
One More Thing
Since I'm learning Ruby, and since I learn by doing, I force myself to write (semi)useful utilities for everyday task, like creating a password for my No-IP account. Instead of just coming up with something I'll remember, like 1 2 3 4 5, I decided to write a string generator. woohoo!
def help()
puts "--Hey, you are doing it wrong--
#{$0} requires a numeric argument
examples:
# create a 20 character string
#{$0} 20
# create a 10 character string
#{$0} 10
"
end
#what chars do we have to pick from?
chars = "!@$%^*_+=ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
#get the first argument as an integer
num = ARGV[0].to_i
#the num better exist, and it better not be zero!
if num.nil? or num.zero?
help()
exit()
end
charslen = chars.length
string = ''
(1..num).each do
char = chars[ rand(charslen) ]
string << char
end
puts string
Sweet! Now quit reading, and go learn something new.