IP Upload Script

Query's a server for a webpage that contains the public IP of the computer this script is run from. It parses the webpage for the IP address and then uploads it to an FTP server.

This script should run on any computer that has ruby installed.

Make sure you edit the configuration bit at the top of the file to suit your needs.

#!/usr/bin/ruby
 
############################################
# Simple script to upload current public IP
# address to an ftp server.
#
# Requires a cooperating server to determine
# public IP address
#
# Author: Martin Gill <martin@martinsgill.co.uk>
# Copyright (C): Martin Gill, 2007 
# License: GPL v2 (see http://www.gnu.org/licenses/gpl.txt).
############################################
 
require 'net/http'
require 'net/ftp'
require 'uri'
require 'tempfile'
 
### CONFIGURATION ###
 
ipPage  = 'http://www.example.com/ipaddy.html'
ftpPage = 'ftp://user:pass@www.example.com/ip.txt'
				 # if you include user:pass in this ftp site
				 # make sure you set the file permissions
                 # so that only authorised users may read this file.
 
#####################
 
#Grab the webpage from the server
page = Net::HTTP.get(URI.parse(ipPage))
 
ipAddress = ""
 
#pull our IP address from the web page
page.each do |line|
	# this regex finds an IP address on a line of the format "Your IP{...} 123.123.123.123"
	# I have my server configured so that it returns the callers IP when they get a 404 error
    match = /Your IP.+\b((?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))\b/.match(line)
    if match
        ipAddress = match[1]
        break #give up once we have an IP address
	end
end
 
# ok.. if we have the IP address, upload the address
unless ipAddress == ""
	#create a temp file that we can upload
	temp = Tempfile.new("ipUploader")
	temp.puts ipAddress
	temp.flush # ensure the ip we added is written to disk
 
	uri = URI.parse(ftpPage)
	Net::FTP.open(uri.host, uri.user, uri.password) do |ftp|
		#extract target dir and filename
		dir, base = File.split(uri.path)
		#change remote directory	
		files = ftp.chdir(dir)
		#upload the IP address
		ftp.puttextfile(temp.path(), base )
	end
end
miscellany/ip_upload_script.txt · Last modified: 2008/08/05 10:57 by martinsgill
Firefox 3 Mandriva Linux National Secular Society Humanism Lib Dems