Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/perl
- use strict;
- use warnings;
- # ---------------------------------------
- # ------- ipchange_notify.pl ------------
- # ---------------------------------------
- # Version: 0.7a
- # Check for changes in WAN IP address
- # (dynamic). If there is a change since
- # the last check, send new IP in email.
- # ---------------------------------------
- # 2011-02-01
- # By: Philip Smith
- # ---------------------------------------
- use Data::Dumper;
- use Email::Send;
- use Email::Send::Gmail;
- use Email::Simple::Creator;
- use HTML::Strip;
- use LWP::Simple;
- use Path::Class qw( file );
- use YAML qw( LoadFile );
- use YAML::Dumper;
- # load conf yaml
- my $config_dir = '.config';
- my $default_conf = file( $config_dir, '', 'ipchange_notify.yaml' );
- my $config = LoadFile( -e $default_conf
- ? $default_conf
- : die "Cannot load conf! $@\n" );
- # check wan ip4 address
- my $url = $config->{urls}{check_ip};
- my $old_ip = $config->{local_info}{old_ip};
- my $new_ip = get_ip($url);
- my $diff = 0;
- if ( $new_ip ne $old_ip ) {
- $diff = 1;
- send_email();
- update_conf();
- }
- sub update_conf {
- my $fh_r;
- my $fh_w;
- my $file = './.config/ipchange_notify.yaml';
- open( $fh_r, '<', $file )
- or die "Cannot open $file to read: $!\n";
- my $line;
- my @lines = <$fh_r>;
- foreach $line ( @lines ) {
- if ( $line =~ m/$old_ip/ ) {
- $line =~ s/$old_ip/$new_ip/;
- }
- }
- close( $fh_r );
- open( $fh_w, '>', $file )
- or die "Cannot open $file to write: $!\n";
- foreach $line ( @lines ) { print $fh_w $line; }
- close( $fh_w );
- }
- sub send_email {
- # set up email object
- my $email = Email::Simple->create(
- header => [
- From => $config->{email_info}{from_email},
- To => $config->{email_info}{to_email},
- Suject => 'IP Address Change Notification',
- ],
- body => "New IP: $new_ip",
- );
- # send the email notification
- my $sender = Email::Send->new(
- { mailer => 'Gmail',
- mailer_args => [
- username => $config->{email_info}{username},
- password => $config->{email_info}{password},
- ]
- }
- );
- eval ( $sender->send($email) ) if $diff;
- die "Error sending email: $@\n" if $@;
- }
- sub get_ip {
- my $url = shift;
- my $html = get("$url")
- or die "Could not fetch index.html: $@\n";
- my $stripper = HTML::Strip->new();
- my $naked = $stripper->parse( $html );
- $stripper->eof;
- $new_ip = $1 if $naked =~ /(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/;
- return $new_ip;
- }
Add Comment
Please, Sign In to add comment