Post Reply 
 
Thread Rating:
  • 0 Votes - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Network Monitor
06-23-2011, 11:25 PM
Post: #1
Network Monitor
Code:
#!/usr/bin/perl

#==============================
#Network Monitor v0.1         +
#Created by: BacklTrack       +
#5/23/2011                    +
#www.pro9ramming.com          +      
#==============================


use warnings;
use strict;
use IO::Socket;
use Time::localtime;

#===========================================================
#$tst_host = Internet host we test                         +
#                                                          +
#$port = ..port                                            +
#                                                          +
#$log_path = Path to our log file to record events         +
#                                                          +
#$sleep_time = Amount in seconds in which our main loop    +
#will pause before continuing.                             +
#                                                          +
#$m_socket = Our main socket OR testing socket             +
#                                                          +
#$connected = our def/undef variable to keep the program   +
#updated on our network's status.                          +
#===========================================================

my( $tst_host, $port, $log_path, $sleep_time, $m_socket, $connected);

open( my $HANDLE, "+<", "default.conf" )
   or die "Could not open $log_path";

#==============================================================
#Read the config file's information.                          +
#Should follow the format of:                                 +
#Line 1: Your host to test ( i.e google.com )                 +
#Line 2: Default port ( i.e 80 )                              +
#Line 3: Log Path(If the file isn't there it WILL be created) +
#Line 4: Sleep time in SECONDS                                +
#==============================================================

($tst_host, $port, $log_path, $sleep_time) = <$HANDLE>;
close ($HANDLE);
&rm_chomp();

if(!&file_exist())
{
   &mk_file();
}

#===============================================================
#Program's main loop.                                          +
#If the connect function fails                                 +
#and we didn't already KNOW the connection                     +
#was down, this is new so log it and tell the                  +
#program we now know.                                          +
#                                                              +
#If the connection is a success(returns anything but undef)    +
#and we already know it's been up, don't do anything.  BUT     +
#If this is a new occurence, log it.                           +
#                                                              +
#Every loop, the program should halt its threads so it's not   +
#hogging all the CPU cycles for something that isn't exactly   +
#critical                                                      +
#===============================================================
while ( 1 )
{
   if( !(&try_connect) )
   {
      if( $connected ne undef )
      {
      &log(&grab_time() . " Internet Disconnected\n");
      $connected = undef;
      }
   }
   else
   {
      if( $connected eq undef )
      {
      &log(&grab_time() . " Internet Currently Connected\n");
      $connected = "Connected";
      }
   }
   sleep( $sleep_time );
}


#=============================================
#Simple log function.                        +
#Attempt to open a file for appending        +
#If success write a String argument to       +
#the file. At the end close the file handle  +
#=============================================

sub log{
   open( my $TMPHANDLE, ">>", $log_path )
      or die "Could not open $log_path : $.";

   my $write_phrase = pop(@_);
  
   print $TMPHANDLE "$write_phrase";
   close( $TMPHANDLE );
}

#========================================
#Just attempt to connect to any website +
#thats known as reliably stable.        +
# i.e www.google.com                    +
#========================================

sub try_connect{

   if( $m_socket = IO::Socket::INET->new("$tst_host:$port"))
   {
      close($m_socket);
      return "Connected";
   }else{
   return undef;
   }
}

#=================================
#Use perl's time module to easily+
#get the current date & time     +
#=================================

sub grab_time{

return (sprintf("%d/%d/%d %d:%d:%d",localtime()->mon, localtime()->mday,
                                    localtime()->year + 1900, localtime()->hour,
                           localtime()->min, localtime()->sec ));
}

#===========================
#Simple check for a file's +
#existence.  Borrowed from +
#perl.about.com            +
#===========================

sub file_exist{
   if( -e $log_path )
   {
      return "exists";
   }
   else
   {
      return undef;
   }
}

#============================
#Open a file for writing to +
#ensure its been created    +
#============================
sub mk_file{
open(my $fHandle, ">", $log_path )
   or die "Could not create $log_path";
close($fHandle);

}

#===================================================
#Just remove the newlines left from reading a file +
#Im aware it's lazy, but hell I'm using perl here. +
#===================================================
sub rm_chomp{

   chomp ($tst_host);
   chomp ($port);
   chomp ($log_path);
   chomp ($sleep_time);
}


Heres some sample output


5/23/2011 9:17:56 Internet Currently Connected
5/23/2011 9:19:19 Internet Currently Connected
5/23/2011 9:19:36 Internet Disconnected
5/23/2011 9:19:56 Internet Currently Connected

.conf file I used
Code:
www.google.com
80
C:\Users\BacklTrack\Desktop\log.txt
5

"Character is determined more by the lack of certain experiences than by those one has had."
Friedrich Nietzsche
Visit this user's website Find all posts by this user
Quote this message in a reply
06-28-2011, 10:52 AM
Post: #2
RE: Network Monitor
Nice and neat code mate, you rock! Smile

Read rules Smile
[Image: legislator.png]
Find all posts by this user
Quote this message in a reply
06-29-2011, 11:59 AM
Post: #3
RE: Network Monitor
I guess clean code in perl is possible Big Grin thanks l3g1s14tor!

"Character is determined more by the lack of certain experiences than by those one has had."
Friedrich Nietzsche
Visit this user's website Find all posts by this user
Quote this message in a reply
07-01-2011, 12:48 PM (This post was last modified: 07-01-2011 12:49 PM by Back_track.)
Post: #4
RE: Network Monitor
Heres version 2.

Changes include:
Optional message box to alert the user about connection changes. ( Looks better on windows than it does *nix )

Code:
#!/usr/bin/perl

#==============================
#Network Monitor v0.1         +
#Created by: BacklTrack       +
#5/23/2011                    +
#www.pro9ramming.com          +      
#==============================


use warnings;
use strict;
use IO::Socket;
use Time::localtime;
use Tk;

#===========================================================
#$tst_host = Internet host we test                         +
#                                                          +
#$port = ..port                                            +
#                                                          +
#$log_path = Path to our log file to record events         +
#                                                          +
#$sleep_time = Amount in seconds in which our main loop    +
#will pause before continuing.                             +
#                                                          +
#$m_socket = Our main socket OR testing socket             +
#                                                          +
#$connected = our def/undef variable to keep the program   +
#updated on our network's status.                          +
#===========================================================

my( $tst_host, $port, $log_path, $sleep_time, $m_socket, $connected, $notify );

open( my $HANDLE, "+<", "default.conf" )
   or die "Could not open $log_path";

#==============================================================
#Read the config file's information.                          +
#Should follow the format of:                                 +
#Line 1: Your host to test ( i.e google.com )                 +
#Line 2: Default port ( i.e 80 )                              +
#Line 3: Log Path(If the file isn't there it WILL be created) +
#Line 4: Sleep time in SECONDS                                +
#==============================================================

($tst_host, $port, $log_path, $sleep_time, $notify) = <$HANDLE>;
close ($HANDLE);
&rm_chomp();

if(!&file_exist())
{
   &mk_file();
}

#===============================================================
#Program's main loop.                                          +
#If the connect function fails                                 +
#and we didn't already KNOW the connection                     +
#was down, this is new so log it and tell the                  +
#program we now know.                                          +
#                                                              +
#If the connection is a success(returns anything but undef)    +
#and we already know it's been up, don't do anything.  BUT     +
#If this is a new occurence, log it.                           +
#                                                              +
#Every loop, the program should halt its threads so it's not   +
#hogging all the CPU cycles for something that isn't exactly   +
#critical                                                      +
#===============================================================
while ( 1 )
{
   if( !(&try_connect) )
   {
      if(defined($connected))
      {
          &log(&grab_time() . " Internet Disconnected\n");
          $connected = undef;

    if($notify)
          {
      &alert_user("Disconnected");
          }
      }
      
   }
   else
   {
      if(!defined($connected))
      {
          &log(&grab_time() . " Internet Currently Connected\n");
          $connected = "Connected";
    if($notify)
          {
      &alert_user("Connected");
         }
      }
      
   }
   sleep( $sleep_time );
}


#=============================================
#Simple log function.                        +
#Attempt to open a file for appending        +
#If success write a String argument to       +
#the file. At the end close the file handle  +
#=============================================

sub log{
   open( my $TMPHANDLE, ">>", $log_path )
      or die "Could not open $log_path : $.";

   my $write_phrase = pop(@_);
  
   print $TMPHANDLE "$write_phrase";
   close( $TMPHANDLE );
}

#========================================
#Just attempt to connect to any website +
#thats known as reliably stable.        +
# i.e www.google.com                    +
#========================================

sub try_connect{

   if( $m_socket = IO::Socket::INET->new("$tst_host:$port"))
   {
      close($m_socket);
      return "Connected";
   }else{
   return undef;
   }
}

#=================================
#Use perl's time module to easily+
#get the current date & time     +
#=================================

sub grab_time{

    return (sprintf("%d/%d/%d %d:%d:%d",localtime()->mon, localtime()->mday,
                                               localtime()->year + 1900, localtime()->hour,
                                localtime()->min, localtime()->sec ));
}

#===========================
#Simple check for a file's +
#existence.  Borrowed from +
#perl.about.com            +
#===========================

sub file_exist{
   if( -e $log_path )
   {
      return "exists";
   }
   else
   {
      return undef;
   }
}

#============================
#Open a file for writing to +
#ensure its been created    +
#============================
sub mk_file{
    my $banner;

    $banner = "++++++++++++++++++++++" . "\n" .
              "+Network Monitor     +" . "\n" .
              "+BacklTrack          +" . "\n" .
              "+www.pro9ramming.com +" . "\n" .
              "++++++++++++++++++++++" . "\n" ;


    open(my $fHandle, ">", $log_path )
           or die "Could not create $log_path";

    print $fHandle $banner;

    close($fHandle);

}

#===================================================
#Just remove the newlines left from reading a file +
#Im aware it's lazy, but hell I'm using perl here. +
#===================================================
sub rm_chomp{

   chomp ($tst_host);
   chomp ($port);
   chomp ($log_path);
   chomp ($sleep_time);
}

#======================================
#Basic MessageBox Clone               +
#Takes A message as the only argument +
#and uses it to dispay internet stat. +
#======================================
sub alert_user{

    my( $status, $window );
    
    $status = pop ;
    $window = MainWindow->new();

    $window->title("Network Monitor Update");
    $window->resizable(0,0);

    $window->Label(
            -text    =>    " " x 20 . "Internet is: $status" . " " x 20
              )->pack(-side => "top");
    
    $window->Button(
            -text     =>    " " x 10 . "OK" . " " x 10,
            -command =>    sub{ $window->destroy }
               )->pack(-side => "bottom");
    
    MainLoop;
}

"Character is determined more by the lack of certain experiences than by those one has had."
Friedrich Nietzsche
Visit this user's website Find all posts by this user
Quote this message in a reply
Post Reply 


Forum Jump:


 Quick Theme: