Skip to content

Instantly share code, notes, and snippets.

@bajorekp
Created February 4, 2017 18:05
Show Gist options
  • Save bajorekp/d7acd5458da86516c4dbd1101c08cbb5 to your computer and use it in GitHub Desktop.
Save bajorekp/d7acd5458da86516c4dbd1101c08cbb5 to your computer and use it in GitHub Desktop.
Monitor looking for changes in IP address. Written in ruby for being cron job.
#!/usr/bin/env ruby
require 'optparse'
require 'net/http'
options = {
last_ip_file: "/var/www/last_ip.txt",
log_file: "/var/www/ip.txt",
daemon: false
}
OptionParser.new do |opts|
opts.banner = """Usage: ip_monitor.rb [options]
Add it to cron job by:
# crontab -e
* * * * * ruby ip_monitor.rb
"""
opts.on("-l", "--log [path]", "Log file path") do |v|
options[:log_file] = v
end
opts.on("-i", "--ip [path]", "Last ip file path") do |v|
options[:last_ip_file] = v
end
opts.on("-d", "--daemon", "Run itself in endless loop") do
options[:daemon] = true
end
end.parse!
def is_valid_ip(ip)
valid_ip_regex = /^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/
!!(valid_ip_regex =~ ip)
end
def get_ip_from(addrs)
uri = URI(addrs)
ip_addr = Net::HTTP.get(uri).strip
is_valid_ip(ip_addr) && ip_addr
end
def get_public_ip
public_ip_providers = ['http://ipinfo.io/ip', 'https://api.ipify.org/', 'https://www.trackip.net/ip']
public_ip_providers.reduce(false) { |any_ip, url| any_ip || get_ip_from(url) }
end
def monit_ip_change(last_ip_file, log_file)
my_current_ip = get_public_ip
my_last_ip = File.exist?(last_ip_file) && File.read(last_ip_file).strip
if my_current_ip != my_last_ip
File.write(last_ip_file, my_current_ip)
File.open(log_file,'a+') { |f| f.write("[#{Time.now}]\tIP change to: #{my_current_ip}\n") }
end
puts my_current_ip
end
if options[:daemon]
sleep(60) && monit_ip_change(options[:last_ip_file], options[:log_file]) until false
else
monit_ip_change(options[:last_ip_file], options[:log_file])
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment