Skip to content

Instantly share code, notes, and snippets.

@heffergm
Created November 10, 2011 17:26
Show Gist options
  • Save heffergm/1355488 to your computer and use it in GitHub Desktop.
Save heffergm/1355488 to your computer and use it in GitHub Desktop.
Get my public IP and send me email if it changes
#!/usr/bin/env ruby
# Get my public IP, store it, and email me if it changes
# Run from cron
require 'rubygems'
require 'net/https'
require 'gmail'
require 'mime'
time = Time.new
STRFTIME = time.strftime("%Y-%m-%d %H:%M:%S")
OLDIPFILE = '/some/dir'
# Functions
def send_email
puts "#{STRFTIME} - Sending email via Gmail..."
recip = 'me@gmail.com'
subject = 'Public IP Address Has Changed'
gmail = Gmail.new('me@gmail.com', 'PASSWORD')
gmail.deliver do
to "#{recip}"
subject "#{subject}"
text_part do
body "#{MYIP}"
end
end
gmail.logout
end
def update_ipfile
puts "#{STRFTIME} - Updating #{OLDIPFILE} with current IP..."
File.open("#{OLDIPFILE}","w") do |f|
f.puts "#{MYIP}"
end
end
# End Functions
# Get IP
begin
url = URI.parse "http://icanhazip.com"
MYIP = Net::HTTP.get_response(url).body
rescue
puts "#{STRFTIME} - error: #{$!}"
abort "#{STRFTIME} - Couldn't connect to icanhazip.com. Exiting."
else
# if oldip doesn't exist or is different than current IP,
# copy current to oldip and send mail
begin
oldip = File.read("#{OLDIPFILE}")
rescue
puts "#{STRFTIME} - Can't find #{OLDIPFILE}."
update_ipfile
send_email
else
# compare MYIP and oldip
if "#{oldip}" != "#{MYIP}"
puts "#{STRFTIME} - Old IP is not the same as new IP... sending email."
send_email
update_ipfile
else
puts "#{STRFTIME} - Old IP is the same as new IP... exiting."
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment