#!/usr/bin/perl use strict; use warnings; $| = 1; open(STDERR, ">>/var/log/constatd.log") || die "Can't write to file: $!\n"; my $arg = shift; my $pid; if ( $arg =~ /^stop$/i ) { &terminate; exit; } elsif ( $arg =~ /^restart$/i ) { &terminate; $pid = &start; } elsif ( $arg =~ /^start$/i ) { if ( -f '/var/run/constatd.lock' ) { print "constatd already running\n"; exit; } $pid = &start; } elsif ( $arg =~ /^status$/i ) { if ( -f '/var/run/constatd.lock' ) { open LOCK, "; close LOCK; print "constatd running with pid $pid[0]\n"; exit; } else { print "constatd is stopped\n"; exit; } } else { print "Unknown argument. Usage: [start|stop|restart|status]\n"; exit; } if ( !$pid ) { my $failed_pass; while(1) { my @servers = ('google.co.uk', 'bbc.co.uk', 'yahoo.co.uk'); foreach (@servers) { my $result = &check_connection($_); if ( $result ) { $failed_pass++; next; } else { $failed_pass = 0; last; } } if ( $failed_pass > scalar(@servers) ) { print STDERR time . ": Reboot required\n"; &reboot_router; $failed_pass = 0; } sleep(300); } } else { print STDERR time . ": contstatd started with pid $pid\n"; open LOCK, ">/var/run/constatd.lock"; print LOCK $pid; close LOCK; } sub start { my $pid = fork(); print "constatd start: [OK]\n" if $pid; return $pid; } sub terminate { my $pid; if ( -f '/var/run/constatd.lock' ) { open PID, "; close PID; $pid = $lock_contents[0]; } else { print "constatd stop: [FAILED]\n"; exit; } print STDERR time . ": contstatd closing pid $pid\n"; if (kill 'KILL', $pid) { print STDERR time . ": Closed pid $pid\n"; print "constatd stop: [OK]\n"; unlink '/var/run/constatd.lock'; } else { print STDERR time . ": PANIC error closing pid $pid $!\n"; print "constatd stop: [FAILED]\n"; } } sub check_connection { my $server = shift; use IO::Socket::INET; my $sock = new IO::Socket::INET ( PeerAddr=>$server, PeerPort=>80, Proto=>'tcp', ); if ($sock) { print STDERR time .": Connection OK to $server.\n"; $sock->close; return; } else { print STDERR time .": Socket could not be created to $server.\n"; return 1; } } sub reboot_router { use LWP::UserAgent; my $ua = LWP::UserAgent->new; $ua->agent("constatd/0.1 "); $ua->credentials( '192.168.0.1:80', 'NETGEAR DG834GT ', 'username' => 'password' ); my $req = HTTP::Request->new(POST => 'http://192.168.0.1/setup.cgi'); $req->content_type('application/x-www-form-urlencoded'); $req->content('Reboot=Reboot&todo=reboot&this_file=diag.htm&next_file=diag.htm'); my $result = $ua->request($req); print STDERR $result->content; }