User Tools

Site Tools


scripts:perl:check_default_route.pl
check_default_route.pl
#!/usr/bin/perl
#
# Written by Thomas York
# Written to record information on when the default route changes
# REQUIRED PACKAGES : perl-Mail-Sender perl-Unix-Syslog
#
 
$|=1;
%interfaces = ();
use Sys::Syslog qw( :DEFAULT setlogsock);
use Mail::Sender;
use POSIX qw/strftime/;
 
###################
# <CONFIGURATION> #
###################
# Should we email about route changes? Set this as 1 to enable, or 0 to disable
$email=1;
 
# Where should we send emails?
$email_to="noc\@domain.tld";
 
# Where should we send emails from?
$email_from="firewall\@domain.tld";
 
# What is the replyto value?
$email_replyto="noc\@domain.tld";
 
# Email subject
$email_subject="Default route change for firewall";
 
# Address of the email server
$email_server="mail.domain.tld";
 
# Email priority (Look at http://jenda.krynicky.cz/perl/Sender.pm.html#item_new_Mail%3A%3ASender)
$email_priority=1;
 
# Set preferred interface for default route
$last_dev = "tun0";
 
# Declare interfaces
$interfaces {"eth0.403"} = "Fiber";
$interfaces {"tun1"} = "Wireless";
$interfaces {"tun0"} = "Cable";
 
####################
# </CONFIGURATION> #
####################
 
# Main program execution
while () {
 
	# Get route list
	$default_route = `ip route list | grep default`;
 
	# Seperate out the information via regex
	if($default_route =~ m/^default via (\S+) dev (\S+).+/) {
		($default_dest, $default_dev) = ($1, $2);
	}
 
	# Check to see if the current default route matches the old default route
	if(!($last_dev eq $default_dev)) { # Route has changed!
		$last_dev = $default_dev;
		setlogsock('unix');
		openlog($0,'','user');
		syslog('info', "Default route changed to $interfaces{$default_dev} ($default_dev)");
		closelog;
		print "Default route changed to $interfaces{$default_dev} ($default_dev)\n";
 
		# Check to see if email logging is enabled
		if ($email) {
			# Build the message string
			$email_text = "The default route on " . $email_from . " changed to " . $interfaces{$default_dev} . " (" . $default_dev . ") at " . strftime('%D %T',localtime) . " (EPOCH " . time() . ")\n\nSent by check_default_route on " . $email_from . ".\nTHIS IS AN AUTOMATED EMAIL! DO NOT REPLY TO THIS EMAIL!\n";
 
			# Send email
			(new Mail::Sender)->MailMsg({ smtp => $email_server, from => $email_from, to => $email_to, replyto => $email_replyto, subject => $email_subject, client => $email_from, priority => $email_priority, msg => $email_text });
		}
	}
 
	sleep 5;
 
}
/usr/local/www/vhost/www.fuhell.com/data/pages/scripts/perl/check_default_route.pl.txt · Last modified: 2014/09/01 15:00 (external edit)