26
Jan
2009
Jan
2009
Tool: checkip.rb
Often I find my self in need of accessing my home network for various reasons but the IP address changes more often than not. So I wrote this little script, that will connect to whatismyip.com and email me if the IP has changed. I also setup a crontab entry that will run the script every hour to look for ip address changes. The code and the crontab are posted below if anyone feels they could use the script. Please let me know if there are any errors or if you need help.
checkip.rb#!/usr/bin/env ruby #Jacob Hammack #http://www.hammackj.com #checkip.rb is a tool to check the internet facing ip and emailing a specific user if the ip changes from the previously noted ip require 'rubygems' require 'open-uri' require 'hpricot' #sudo gem install hpricot require 'net/smtp' $FROM_EMAIL = "FROMEMAILADDRESSHERE" $TO_EMAIL = "TOEMAILADDRESSHERE" # read_ip () reads the locally stored .checkip file for the last known ip # def read_ip() ip = "" begin File.open(".checkip", "r") { |f| ip = f.gets() } rescue => err #file doesn't exist, can ignore it end return ip end # main() checks teh whatismyip.com website for changes in ip address stored locally # def main() puts "checkip.rb\nJacob Hammack\nhttp://www.hammackj.com\n" new_ip = Hpricot(open("http://www.whatismyip.com/automation/n09230945.asp")) new_ip = new_ip.html.chomp ip = read_ip() ip.chomp! unless ip == nil if new_ip != ip puts "[!] Different IP Address Detected emailing admin!" email_admin(new_ip) File.open(".checkip", "w") { |f| f.puts new_ip } else puts "[*] No IP change" end end # email_admin(ip) sends a email to the $TO_EMAIL variable using a local sendmail mta # def email_admin(ip) msg = sprintf "From: checkip.rb <%s>\nTo: %s <%s>\nSubject: Your IP has been updated!\nDate: %s\nMessage-Id: <%s@hammackj.net>\n\nYour IP address has changed to %s\n", $FROM_EMAIL, $FROM_EMAIL, $TO_EMAIL, Time.now, ip, ip Net::SMTP.start('localhost', 25) do |smtp| smtp.send_message msg, $FROM_EMAIL, $TO_EMAIL end end main()
crontab -l[hammackj@frijoles:/opt/scripts]# sudo crontab -l # m h dom mon dow command 0 * * * * /usr/bin/ruby /opt/scripts/checkip.rb