IP Check Script

Since I’m cheap and don’t want to pay for a static IP at home, my dynamic IP changes once in a while. I have dynamic DNS set up on my router, but it occasionally (usually after a power outage) messes up and reports an internal IP (192.168.x.x) and kills DNS. So, I came up with a little perl script to check my IP occasionally (out of cron) and email me if there’s a change. Or, email me if it’s been a week and there’s been no change (sanity check to know it’s working). Or, email me if it can’t reach www.whatismyip.com and get a valid IP address (this was failing on me about once a week before I added the retry loop).

Of course, the email bit is dependent on whether or not you have sendmail or postfix (or another) set up correctly.

I’m still learning Perl, so I have no doubt there are things in the script that will make some programmers cringe - all I can say is I’m sorry and I welcome your feedback. I think I put enough comments in the script to make it self-explanatory.

Cron entry0 */8 * * * /tools/ip_check.pl >> /tools/ip_check.log 2>&1

Script
Download the script here.

#!/usr/bin/perl
#A script to check the current public IP and notify someone via email of any changes
#This script will create/use a file for tracking the last known/checked IP address
#The script uses the automation IP check site provided by www.whatismyip.com:
#http://whatismyip.com/automation.asp

use strict;
use LWP::Simple;
use File::stat;
use Env qw(HOME);

#Print a timestamp
print "\n\n\n\nSTARTING the IP Check at " . localtime(time) . "\n";

#Variables
my $file = "/$HOME/current_ip";  #location of the file to check the IP against and store an updated IP
my $url = "http://www.whatismyip.com/automation/n09230945.asp";  #the address to hit for IP query
my $from_addy = "user_from\@domain.com";  #the FROM email address
my $to_addy = "user_to\@domain.com";  #the TO email address
my $counter = 0;  #the retry counter starts with this number and increments by 1 right away
my $snooze = 60;  #how many seconds to wait before trying to hit the IP URL again
my $trys = 5;  #how many times to retry the IP URL

#Get the last known IP from a file - if the file does not exist, the script will make it later
open LOG, "<$file";
my $logged_ip = ;
close LOG;

#Go check the current public IP and try a few times every X seconds if you don't get a response form the URL
my $output = get $url;
if (($output eq "") and ($counter <= $trys)) {
	while (($output eq "") and ($counter <= $trys)) {
		print "URL output is: $output\n";
		print "No response from $url so sleeping for $snooze seconds before checking again.\n";
		sleep $snooze;
		$counter += 1;
		if (($output eq "") and ($counter == $trys)) {
			print "The check has returned no result after trying $counter time(s) every $snooze seconds - sending an email and dying.\n";
			open (MAIL, "|/usr/sbin/sendmail -t ");
	                print MAIL "From: $from_addy\n";
        	        print MAIL "To: $to_addy\n";
                	print MAIL "Content-Type: text/plain\n";
	                print MAIL "Subject: IP Address Check Failed\n\n";
        	        print MAIL "I have tried to check the IP $counter times every $snooze seconds and am getting no response.\n\nI'm going to die now and hope that the next check works.\n\nThe last time I checked the IP was: $logged_ip\n";
	        close (MAIL);
		exit;
		} else {
		print "\nDone sleeping and am tyring the check again...\n";
		print "Counter is at: $counter\n";
		$output = get $url;
		}
	}
	print "Success! The check timed out $counter time(s) before finally returning a result: $output\n";
}
print "IP on record: $logged_ip\n";

#Compare the IPs and email if they're different
if ($logged_ip ne $output) {
	print "The IP has changed, so I'm updating the IP log file and sending an email with the change\n";
	print "The IP reported was $output\n";
	open LOG, ">$file";
	print LOG $output;
	close LOG;
	open (MAIL, "|/usr/sbin/sendmail -t ");
		print MAIL "From: $from_addy\n";
		print MAIL "To: $to_addy\n";
		print MAIL "Content-Type: text/plain\n";
		print MAIL "Subject: IP Address has changed to $output\n\n";
		print MAIL "Your home IP Address has changed from $logged_ip to $output\n\nGo check DNS and fix if needed.\n";
	close (MAIL);
} else {
#If the IP address hasn't changed, check the file age and email an update if it's over a week old - then update the file's time stamp
	my $st = File::stat::stat($file);
	my $age = time - $st->mtime;
	my $days = int($age/(24*60*60));
	my $hours = ($age/(60*60))%24;
	my $mins = ($age/60)%60;
	my $secs = $age%60;
	my $how_old = "$days days, $hours hours, $mins minutes, $secs secs";
	print "Age of the IP record file: $how_old\n";
	if ($age > 604800) { #604800 is seconds/week - could variablize this if it was to change often
		print "The IP is the same, but the log file is over a week old so I'm going to send an update\n";
		        open (MAIL, "|/usr/sbin/sendmail -t ");
				print MAIL "From: $from_addy\n";
				print MAIL "To: $to_addy\n";
				print MAIL "Content-Type: text/plain\n";
				print MAIL "Subject: Weekly Update: IP Address has NOT changed\n\n";
				print MAIL "Your home IP Address has NOT changed in over a week and is still $output.\n\nThe file was this old: $how_old\n\n";
				close (MAIL);
		print "Mail sent.\n";
		my $now = time;
		utime $now, $now, $file;
		print "File touched to update the timestamp.\n";
	} else {
#If the IP's the same and it's been less than a week since the last email - don't do anything
		print "The current IP ($logged_ip) matches the checked IP ($output) and it's been less than a week since the last send so there is nothing to do.\n";
	}
}

Xubuntu, Novatel U727 and VPN (PPTP)

For my future reference:

From: http://blogfranz.blogspot.com/search/label/EVDO
Add vendor and product options to /etc/modules

usbserial vendor=0x1410 product=0x4100

Disable automounting of USB serial devices with gnome-volume-properties (didn’t do this in Xubuntu - just eject the automounted SMB CD thing)

Otherwise the USB Serial devices won’t show up and you would have to unmount WTF that image that is being mounted from the

Create /etc/ppp/peers/sprint
/dev/ttyUSB0 # modem
115200 # speed
921600 # works, abt 60kbytes/sec on S620
#1036800 # doesn't work
defaultroute # use cellular network for default route
usepeerdns # use the DNS servers from the remote network
nodetach # keep pppd in the foreground
crtscts # hardware flow control
lock # lock the serial port
noauth # don't expect the modem to authenticate itself
local # don't use Carrier Detect or Data Terminal Ready
user
ppp
#passive
debug
lcp-echo-failure 4 # prevent timeouts (1of2)
lcp-echo-interval 65535 # prevent timeouts (2of2)
connect "/usr/sbin/chat -v -f /etc/chatscripts/sprint-connect"

Create /etc/chatscripts/sprint-connect

TIMEOUT 10
ABORT 'BUSY'
ABORT 'NO ANSWER'
ABORT 'ERROR'
SAY 'Starting SPRINT connect script\n'

# Get the modem's attention and reset it.
"" 'ATZ'
# E0=No echo, V1=English result codes
#OK 'ATE0V1'

OK 'ATDT#777'
CONNECT

Start pppd

root@gutsy61:~# pppd call sprint
Starting SPRINT connect script
Serial connection established.
using channel 1
Using interface ppp0
Connect: ppp0 <--> /dev/ttyUSB0

VPN:
From comments at this post: http://www.ubuntugeek.com/howto-connect-to-windows-vpn-server-pptp-with-ubuntu-710-gutsy-gibbon.html

- Install package pptp-linux

- Create file /etc/ppp/peers/YOUR_COMPANY with the this content:
-I kept getting an “unrecognized option” error until I deleted and reinserted the quotes on this line - there was some funky formatting with them that persisted even after pasting in vim

pty “pptp YOUR_VPN_GATEWAY –nolaunchpppd” # delete and reinsert the quotes
debug
nodetach
logfd 2
noproxyarp
ipparam YOUR_COMPANY
remotename YOUR_COMPANY
name YOUR_DOMAIN_OR_SERVER_NAME\\YOUR_VPN_LOGIN
require-mppe-128
nobsdcomp
nodeflate
lock
noauth
refuse-eap
refuse-chap
refuse-mschap

- add to /etc/ppp/chap-secrets:
YOUR_DOMAIN_OR_SERVER_NAME\\YOUR_VPN_LOGIN * YOUR_VPN_PASSWORD *

- Create file /etc/ppp/ip-up.d/add-subnet with content similar to:
#!/bin/bash
[ "$PPP_IPPARAM" = "YOUR_COMPANY" ] || exit 0
route add -net 192.168.100.0/24 gw $PPP_LOCAL

In the above line, adjust subnet values (192.168.100.0/24) if needed

- Make /etc/ppp/ip-up.d/add-subnet executable

- Connect to VPN:
sudo pon YOUR_COMPANY
To disconnect, press Ctrl+C or close the terminal.

- If you do not want to see VPN connection debug output, in file /etc/ppp/peers/YOUR_COMPANY delete 3 lines:
debug
nodetach
logfd 2

In this case, “pon YOUR_COMPANY” will run as a background process. Use “poff YOUR_COMPANY” to disconnect.

keywords: ubuntu xubuntu novatel u727 vpn pptp sprint linux hardy

I’ll Pass On the Blast

I had a flyer on my door the other day for the new and improved Comcast Blast – it offered 16MB download and 2MB upload (my current service is 6MB/1.5MB). Always one to be interested in faster/better when it comes to gadgets/technology, I called about it. Basically it’s free for 3 months then it jumps to $10/month extra. Wonder of wonders, I actually declined trying it for three reasons: 1) with stuff like that I usually forget to call and end up eating a month or two before I get it canceled, 2) even though I only technically have 6MB/1.5MB, usually my download speed is more in the 10MB range which is plenty fast enough and 3) I’m already paying Comcast $58/month for my internet after modem leas and taxes(we don’t have cable/TV so that is the internet price only) and would like to decrease the price – not be tempted to increase it!

I actually used the call to try to get some promotional pricing or a discount, but the rep I talked to was less than caring and instead tried to get me to sign up for their cable or phone service (I use Vonage currently). I even mentioned that Verizon FiOS is in our neighborhood and was competing for my business – she didn’t seem to be concerned about that either. Of course I didn’t tell her that I would learn Morse code and buy a telegraph before I use Verizon for anything again. So, I guess I’m still stuck with my fairly fast and fairly expensive internet for now.

Linux Training: Addendum

So, a few weeks ago I commented on Red Hat and O’Reilly’s training. Since then I’ve had additional experiences with them that has helped to change my opinion some.

Red Hat: While I still feel the class was great (RH253), they have now canceled their RHCE test (RH302) in the Seattle area for the second time in a row! First in April, now in May. The next test in Seattle (Bellevue) isn’t until July – that’s a long time to remember the material from my class in April. When I emailed them to ask why it had been canceled, their less-than-clear response was basically that there wasn’t enough interest. I was interested.

O’Reilly School of Technology: This one was rather disappointing. I was all excited when I started taking the Linux/Unix 4: Scripting for Administrators Sed, Awk, and Perl course, but I didn’t get far into it before realizing it just wasn’t very good. The lessons were really short and didn’t seem very thorough. Then, the Objectives and/or Quizzes at the end of each lesson often asked questions on things that weren’t covered in the lesson at all. I re-read a couple lessons a few times to make sure I didn’t miss it (which didn’t take long because, again, the lessons were really short). Then (while searching for an answer to a question that wasn’t covered in the lesson), I found this page and figured that between that and my Learning Perl book (which has exercises at the end of each chapter) I could probably get the same (or more) material w/o paying a few hundred dollars. One good thing is that the O’Reilly course has a 7 day money back guarantee. Maybe their other courses are better, but this one was not worth the money.

Conclusion: Red Hat training is great – just don’t rely on them sticking to their course/test schedule. O’Reilly is an awesome book publisher – but their online course (at least the one I took) is a little lacking.

Update: After I had written this (be pre-posting) I got a call from a support rep at O’Reilly regarding my cancellation. She was extremely helpful and friendly and understanding. The cancelation was a really easy process. Darn it, O’Reilly – you have everything in place – you just need to add a little more to your lessons or ask questions in the Quizzes/Objectives that were actually covered in the lesson.

VirtualBox Rocks!

I’ve been using Virtual PC 2007 for a while to run a Linux guest inside of Vista. I’ve also been using MS Virtual Server and some of our production stuff runs on VMware ESX. I used VMware Workstation for a few months as well. And, I’ve briefly played with Xen. So, all that to say that I am fairly comfortable and familiar with virtualization.

While trying to get various Linux distros to run in Virtual PC (most recently Ubuntu 8.04) I kept running into posts about VirtualBox by Innotek (recently acquired by Sun). So, today I thought I would give it a try.

First impressions: WOW! It’s a great piece of software and is well on its way to replacing Virtual PC for me. It has USB support (something Virtual PC lacks). It’s fairly easy to use and seems to be more feature rich than VPC. Also, Ubuntu 8.04 in it.

I’m curious if other Linux distros will install as flawlessly (no i8042.noloop or other tricks needed?) - my assumption is yes.

Update: I just installed Fedora 8 w/o any problems as well. Again, no “vesa i8042.noloop”, no “clock=pit”, nothing - it just worked. And, a week or so ago when I installed Fedora 8 on VPC, a kernel upgrade completely killed it. Not on VirtualBox - it booted up like a champ after the kernel upgrade.

Linux Training

I recently finished the RH253VT course (Red Hat training to acquire the RHCE) and really enjoyed it. Before enrolling, though, I spent a significant time searching for Linux training courses and really didn’t find too much.

Just today in my inbox I had an email from O’Reilly (the book publishers) about some courses they offer in partnership with the University of Illinois: The O’Reilly School of Technology. It seems like pretty solid training and I’m thinking I might try and do the Linux/Unix 4: Scripting for Administrators Sed, Awk, and Perl course in the future. I think it’s a little funny that they charge $19.90/month for their online lab (Unix) and Red Hat charges $499/week (no, I did not mess up those numbers). Red Hat’s virtual lab was pretty good (although I think they’re still working out a few bugs) and I haven’t seen what O’Reilly’s is like, but we’re talking about 1/100 of the price!

On a side note, I also subscribe to O’Reilly’s Safari online book e-library thingy. It’s a great resource as well.

Weird Sophos/Vista Issue

I had a weird issue with Sophos on my personal laptop that I think was worth posting. For a number of days Sophos wasn’t updating (and had the little red X on it). Every time it tried updating, it failed with the following error in the event logs:
Product: Sophos Anti-Virus -- Error 1406.Could not write value DisableMonitoring to key \SOFTWARE\Microsoft\Security Center\Monitoring\SophosAntiVirus. System error . Verify that you have sufficient access to that key, or contact your support personnel.

When I would go into regedit and drill down to Monitoring, I would get a permissions error. Here’s what I did to resolve it:

1) Turned off UAC (not sure if this is needed)
2) Right click on Security Center and select Permissions
3) Click on the Advanced button
4) Click on the Owner tab
5) In the Change owner box, I selected my user account - OK your way out of it

From this point, I’m not sure where I went next. I think now I was able to click on Monitoring and see the keys in there, but was still getting permissions issues…but I think I was now able to right click on Monitoring and select Permissions and was able to add my account with Full Control (I added the Administrator account for good measure).

What was weird was that as soon as I did that more accounts were added with permissions (similar to other keys) and suddenly there was some McAfee keys in there (I previously had McAfee installed before Sophos). I tried a Sophos update and it succeeded!sophos_Error_1406.JPG

So, I apologize for the lack of detail after changing the owner, but I’m pretty sure the owner change was the important step and that you’ll be able to figure it out from there. I also went back and changed the Owner back to SYSTEM. Again, not sure if that is needed and/or will break things later, but I figured it was a prudent step.

Windows Home Server Eval

Not sure how long this has been up - I hadn’t checked it in a while. You can get a 120 day eval of Windows Home Server for free. It isn’t available for download yet, so you have to pay $5.99 for shipping. And, if you live in WA, they charge your tax on the shipping (what?). So, for the low price of $6.52, you can take WHS for a test drive.

http://www.microsoft.com/windows/products/winfamily/windowshomeserver/eval.mspx

I’ll post an update after I get mine and have some time to play with it.

Home NAS - VNC

I’m not sure how this slipped by me, but I wasn’t really aware of VNC until I started looking for a solution to “remote desktop” in to the Mac Mini. Apple makes a product that looks pretty cool, Apple Remote Desktop 3, but it’s more for system administrators in Mac networks….and costs $300 (cheapest option – 10 clients). So, my co-workers mentioned VNC.

The solution I used for the Mac Mini was to install Vine Server (free) as the VNC server (that sits on the Mac and listens for connections). As for connecting to the Mini, I used RealVNC for connecting from our client laptops (VNC viewer).

VNC Screenshot

Why use products (server and viewer) from two different vendors? Well, the Vine Server was free, but the Vine Viewer costs money. And I’m pretty cheap. So, for now I’ll use the free solutions (and so far they are working great!). Maybe later after I get a feel for what my needs are I’ll look for a different solution and even be willing to shell out a couple of bucks.

Of course, VNC works remotely, too. Just open up a port in your firewall and you can connect from anywhere. I still need to secure it a little better, but I want to give more thought to that. SSH…VPN…???

Home NAS – The Overall Project

Not really a business or enterprise class project, but something fun I thought I would chronicle. I’ve been giving a lot of thought to my existing home network. You know what they say, the mechanic is the guy with the car that doesn’t run, the electrician is the one with bad wiring in his house, the financial advisor is the guy that’s broke…well, in this case, the IT guy is the one with a very outdated and unstable home network. I figure it’s finally time to do something about it and have put a lot of thought into it.

Current Set Up
Right now I have a 1.7GHz Celeron homebrewed PC running Windows XP as my main desktop computer. The only problem is that the desk it is at is so buried, it’s pretty much unusable as a workstation. So, I’ve been using it mainly for iTunes downloads and iPod syncing and as a file share for our digital camera pictures and other documents. I remote desktop into it whenever I need something (from home or externally). It crashes every few days and there is no data redundancy. If the HDD fails, I’m toast.

My wife and I both have laptops with wifi, so we just work off of those (browse, email, watch movies, etc.).

NAS Options
Essentially, I want to replace the desktop with a NAS solution. I saw the D-Link DNS-323 and really like it a lot! It’s got all the features I think I would need and I love the form factor. But, I’m not sure if I want to shell out $175+ for it.

So, I got to thinking about the option of building my own NAS. I have a newer micro-tower PC that I’m not using that could house it. I’m very interested in Windows Home Server as the platform, but it looks like I missed the beta downloads and now they’re in that limbo state where it’s not quite released yet. So, I’m left with using Linux…which isn’t a bad thing, I’m just more comfortable in Windows. But, I figure this would be a good project for me to get even more familiar with Linux.

There are a few Linux NAS solutions out there and I figure I’ll try different ones out to see what one I like best. Two of the more popular are Openfiler and FreeNAS. I’ve played with both a little, but haven’t really gotten a good look yet.

Hardware
For redundancy, I will install a PCI SATA RAID card and two SATA drives, set up in a RAID 1 (mirror) configuration. That way, if a drive fails, all of our data is safe. I don’t have a ton of data, so I figure 200GB or better drives will last us a number of years. My co-worker thinks I’ll be in trouble using a sub-$20 SATA card, so we’ll see…I hope he’s wrong, but he usually isn’t.

Mapped Network Drives
After the NAS is configured, then I’ll just set up a couple of mapped network drives on the two Windows laptops for access to all of our files/data.

iTunes and iPod Syncing
This is probably my favorite part of the new set up. I was able to pick up an old (1st gen, base model) Mac Mini (upgraded to 1GB of RAM, though) that’s only purpose will be to run iTunes and sync up the iPods. It will use the NAS for storage (since its 40GB HDD won’t hold many BSG and Office episodes). We also use our laptops to connect to iTunes for watching TV shows, so the Mac Mini will continue to serve that up as well. I didn’t realize the Mini came with wifi and thought I would have to get a USB adapter, but was pleasantly surprised to find it already in there. The Mini will run headless and I’ll connect to it via VNC. The only cables plugged into it will be power and the iPod USB connecter cable (that’s how I sold my wife on this project…the promise of less wires/cables). On top of the Mini (or somewhere nearby) will sit the iPod Dock. The Mini will also live near our $40 Wal-Mart stereo with auxiliary input, so we can play music from it. We don’t have a TV (cut the cable!), so we’ll continue to use the laptops for the occasional iTunes TV show (farewell Office and BSG, though) and movies.

I’ll post updates regarding the project as I go along. I’ll also go back and cover a few things in more detail and hopefully post some Visio diagrams (because everything looks cooler in Visio).

Next Page »