Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Sylvain Le Courtois

« Newer Snippets
Older Snippets »
Showing 1-4 of 4 total  RSS 

Perl : scan a list of networks, looking for hosts responding on the port 80 (http)

// Input : a list of address of routers, in dotted decimal notation
   1  
   2  use strict;
   3  use Net::Ping;
   4  use IO::Socket::INET;
   5  
   6  sub isodate() {
   7          my ($day, $mon, $year, $hour, $min, $sec) = (localtime)[3, 4, 5, 2, 1, 0];
   8          $mon++; # 0-based index
   9          $year = $year + 1900;
  10          my $date = sprintf ("%04i-%02i-%02i %02i\:%02i\:%02i", $year, $mon, $day, $hour, $min, $sec);
  11          return $date;
  12  }
  13  
  14  sub testhost {
  15         my $p = new Net::Ping("tcp");
  16         $p->{port_num}=80; 
  17         my @result = $p -> ping($_[0],2);
  18         return $result[0];
  19         }
  20  
  21  sub to_dot {
  22  	my $n = shift;
  23  	my @decimal;
  24  	for (1..4) {
  25  		unshift @decimal, $n & 0xFF;
  26  		$n >>= 8;
  27  	}
  28  	return join(".",@decimal);
  29  }
  30  
  31  my %dejavu;
  32  open FH,"liste.txt";
  33  while (<FH>) {
  34  	chomp;
  35  	my ($routeur,$mask)=split;
  36  	
  37  	next if $routeur !~ /\d+\.\d+\.\d+\.\d+$/ or $mask !~ /\d+\.\d+\.\d+\.\d+$/;
  38  	
  39  	next if defined($dejavu{$routeur});
  40  	$dejavu{$routeur}=1;
  41  	
  42  	my ($o1,$o2,$o3,$o4) = split /\./,$mask;
  43  	my $mask=$o1*256**3+$o2*256**2+$o3*256+$o4;
  44  	my $num = $mask ^ 0xFFFFFFFF;
  45  	$num--;
  46  
  47  	my ($o1,$o2,$o3,$o4) = split /\./,$routeur;
  48  	my $net=$o1*256**3+$o2*256**2+$o3*256+$o4 & $mask;
  49  	
  50  	#print join("|",$routeur,&to_dot($net),$num)."\n";
  51  	
  52  	print "Starting scanning network ".to_dot($net).", router = ".$routeur."\n";
  53  	print "Adresses demarrant de ".to_dot($net+1)." et finissant a ".to_dot($net+$num).".\n";
  54  	for my $i (1..$num) {
  55  		my $host=to_dot($net+$i);
  56  		if ( &testhost($host) ) {
  57  			print "$host is alive\n";
  58  			my $port=80;
  59  			my $sock = new IO::Socket::INET (PeerAddr => $host,
  60  					     PeerPort => $port,
  61  					     Proto => 'tcp');
  62  			if ($sock){
  63  				close $sock;
  64  				print "$port -open on $host\n";
  65  				open OUT,">>webservers.txt";
  66  				print OUT join("|",isodate(),$host,to_dot($net),$routeur)."\n";
  67  				close OUT;
  68  			}	else	{
  69  				print "$port -closed on $host\n";
  70  			}
  71  
  72  		} else {
  73  			print "$host is not responding\n";
  74  		}
  75  	}
  76  }
  77  
  78  
  79  close FH;

Browser automation using perl LWP

// This is a sample code used to measure reports response times on a OAS application.
   1  
   2  #!/usr/bin/perl
   3  #
   4  # LWP connection to the Datamart Portal
   5  # Timing of the main reports
   6  #
   7  
   8  use strict;
   9  require LWP::UserAgent;
  10  
  11  my $ua = LWP::UserAgent->new;
  12  
  13  sub isodate() {
  14          my ($day, $mon, $year, $hour, $min, $sec) = (localtime)[3, 4, 5, 2, 1, 0];
  15          $mon++; # 0-based index
  16          $year = $year + 1900;
  17          my $date = sprintf ("%04i-%02i-%02i %02i\:%02i\:%02i", $year, $mon, $day, $hour, $min, $sec);
  18          return $date;
  19  }
  20  
  21  sub datamart_login {
  22          my ( $user, $pass ) = @_;
  23          my $time_begin=time();
  24          my $url='http://daprd:7782/portal/page?_pageid=37,134413,37_134422&_dad=portal&_schema=PORTAL';
  25          my $req = HTTP::Request->new( GET => $url );
  26          my $resp = $ua->request($req);
  27          my $loginform = $resp->content ;
  28          if ( $loginform !~ /Entrez votre nom utilisateur/ ) {
  29                  die isodate()." Failed to get the logon page of the Web Site\n";
  30          } else {
  31                  my $locale="";
  32                  my ($v) = $loginform =~ /NAME=\"v\" value=\"(.+)\"/;
  33                  my ($site2pstoretoken) = $loginform =~ /NAME=\"site2pstoretoken\" value=\"(.+)\"/;
  34                  my ($submiturl) = $loginform =~ /form method=\"POST\" action=\"(.*?)\"/;
  35                  $resp = $ua->post( $submiturl,
  36                     [
  37                       ssousername => $user,
  38                       password => $pass,
  39                       v => $v,
  40                       locale => $locale,
  41                       site2pstoretoken => $site2pstoretoken
  42                     ],
  43                  );
  44                  $resp = $ua->get($url);
  45                  $resp = $ua->get($url);
  46                  if ( $resp->content !~ /Crit..res de recherche/ ) {
  47                          die isodate()." Failed to get the main page of Portal\n";
  48                  }
  49          }
  50          print join(";",isodate(),"Time to log on the Portal",time()-$time_begin,$url)."\n";
  51  }
  52  
  53  sub datamart_testurl {
  54          my ($label,$url,$expected)=@_;
  55          my $time_begin=time();
  56          my $resp;
  57          $resp = $ua->get($url);
  58          $resp = $ua->get($url) if $resp->content !~ /$expected/;        # We try two times !
  59          if ( $resp->content !~ /$expected/ ) {
  60                  print STDERR isodate()." Test Failed on $label. $expected not found in response.\n";
  61                  print STDERR $resp->as_string;
  62          } else {
  63                  print join(";",isodate(),$label,time()-$time_begin,$url)."\n";
  64          }
  65  }
  66  
  67  $ua->timeout(1200);
  68  $ua->cookie_jar({});
  69  $ua->agent( 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)' );
  70  #push @{ $ua->requests_redirectable }, 'POST';
  71  
  72  # >>>> Main code here
  73  
  74  datamart_login("xxxx","xxxx");
  75  
  76  open FH,"/exploit/scripts/appli/check_datamart.ini" or die "Unable to open check_datamart.ini";
  77  while (<FH>) {
  78          chomp();
  79          my ($report,$expected,$url) = split /;/;
  80          datamart_testurl($report,$url,$expected);
  81  }
  82  close FH;
  83  
  84  # <<<< Main code here
  85  

Internet Explorer automation using win32::OLE

// Sample code used for one of my client
   1  
   2  #!/usr/bin/perl -w
   3  
   4  use strict;
   5  use Data::Dumper;
   6  use Win32::OLE qw( EVENTS );
   7  
   8  my ($day, $mon, $year, $hour, $min, $sec) = (localtime)[3, 4, 5, 2, 1, 0];
   9  $mon++; # 0-based index
  10  $year = $year + 1900;
  11  my $date = sprintf ("%04i-%02i-%02i %02i\:%02i\:%02i", $year, $mon, $day, $hour, $min, $sec);
  12  
  13  my $Disconnect;
  14  my $Menu;
  15  my $TreeView;
  16  my $WatchDog;
  17  my $MenuClicked=0;
  18  
  19  my $ScenarioCompleted=0;
  20  
  21  my @TreeViewLinks=("Appareillage du B","Branchement Comptage","Branchement individuel");
  22  my $Previouslink=$TreeViewLinks[0];
  23  
  24  my $ie = Win32::OLE->new( 'InternetExplorer.Application' ) or die "error starting IE";
  25  $ie->{visible} = 1;
  26  
  27  Win32::OLE->Option( Warn => 3 );
  28  
  29  $WatchDog=time();
  30  Win32::OLE->WithEvents( $ie, \&Event, 'DWebBrowserEvents2' );
  31  $ie->navigate( 'http://www.xxx.fr' );
  32  Win32::OLE->MessageLoop();
  33  unlink("noemis.err") if -f "noemis.err";
  34  if ( ! $ScenarioCompleted ) {
  35  	open( ERR , ">noemis.err" ); 
  36  	print ERR "Problem executing Noemis scenario, please check www.xxx.fr.\n" ;
  37  	close(ERR);
  38  }
  39  $Disconnect->Click();
  40  Win32::OLE->SpinMessageLoop;
  41  
  42  # Maintenance du fichier historique
  43  open ( STATS , "noemis.txt" );
  44  my @lines=<STATS>;
  45  close (STATS);
  46  open( STATS , ">noemis.txt" ); 
  47  for my $line (@lines) {
  48  	my ($datetime) = split ( /;/ , $line );
  49  	my ($h_year,$h_mon) = $datetime =~ /^([0-9]{4})-([0-9]{2})/;
  50  	print STATS $line if ($year*12+$mon) - ($h_year*12+$h_mon) < 2;
  51  }
  52  print STATS join(";",$date,"Noemis Scenario",( time() - $WatchDog ))."\n";
  53  close( STATS );
  54  
  55  sleep 2;
  56  Win32::OLE->SpinMessageLoop;
  57  sleep 1;
  58  $ie->Quit();
  59  exit 0;
  60  
  61  
  62  sub Event {
  63  	my ($Obj,$Event,@Args) = @_;
  64  	my $IEObject = shift @Args;
  65  	print " Event triggered: $Event\n";    
  66  
  67  	my ($i,$anchor);
  68  	my $anchors;
  69      
  70  	# STEP 1 : Find the main menu, login to the web site, find the treeview
  71  	if ($Event eq "DocumentComplete") {    
  72  		print "URL: " . $IEObject->Document->URL . "\n";
  73  		if ( $IEObject->Document->URL eq "http://www.xxx.fr/ident.aspx" ) {
  74  			my $forms = $IEObject->Document->forms;
  75  			my $form = $forms->item(0);
  76  			if ( defined($form->elements("fldNumCli")) ) {
  77  				print "--------------------------------------------\n";
  78  				print "Found the login box, authenticating ...\n";
  79  				print "--------------------------------------------\n";
  80  			    $form->elements("fldNumCli")->{value} = "xxxx";
  81  			    $form->elements("fldUtil")->{value} = "xxx";
  82  			    $form->elements("fldPwd")->{value} = "xxx";
  83  		    	$form->elements("btIdent")->Click();
  84  	    		}
  85  		}
  86  		if ( $IEObject->Document->URL eq "http://www.xxx.fr/menu.aspx" ) {
  87  			print "Found the menu.\n";
  88  			$Menu = $IEObject->Document;
  89  			$anchors = $IEObject->Document->links;
  90  			for (my $i=0; $i < $anchors->length; $i++) {
  91  				$anchor = $anchors->item($i);
  92  				print $anchor->href."\n";
  93  				$Disconnect = $anchor if $anchor->href eq "http://www.xxx.fr/ident.aspx?qs=deconnecter";
  94  			}
  95  	      	}	    
  96  		if ( $IEObject->Document->URL eq "http://www.xxx.fr/client/frameTreeview.aspx" ) {
  97  			print "Found the TreeView.\n";
  98  			$TreeView = $IEObject->Document;
  99        		}		
 100  	}
 101  
 102  	# STEP 2 : Click on the Menu and TreeView links   
 103  	if ($Event eq "DocumentComplete") {    		
 104  	if ( ! $MenuClicked and defined($Menu) ) {
 105  		my $MenuItem = $Menu->getElementById("SM_CLIE_RECH");
 106  		if ( defined($MenuItem) ) { 
 107  			print $MenuItem->ID."\n";
 108  			$MenuItem->Click;
 109  			$MenuClicked = 1;
 110  		}
 111  	}}
 112  
 113  	if ( $Event eq "CommandStateChange" or $Event eq "StatusTextChange" ) {
 114  		print Dumper($IEObject);
 115  	}
 116  	if ( @TreeViewLinks != 0 and 
 117  	     defined($TreeView) and 
 118  	     $Event eq "DocumentComplete" 
 119  	) {
 120  		my $link = shift(@TreeViewLinks);
 121  		$anchors = $TreeView->links;
 122  		my $found=0;
 123  		print "Looking for '$link' in the TreeView ... \n";
 124  	        for (my $i=0; $i < $anchors->length; $i++) {
 125  		       	$anchor = $anchors->item($i);
 126  	        	#print $anchor->innerHTML."\n";
 127  		       	if ( $anchor->innerHTML =~ /$link/ ) {
 128  				print "Clicking on '$link' ... \n";
 129  	                	$anchor->Click;
 130  				$found=1;
 131  				$Previouslink=$link;
 132  				last;
 133  			}
 134  	        }
 135  		if ( ! $found ) { 
 136  			# Le TreeView a bugge, on reclique
 137  			sleep 1;
 138  			print "Looking for '$Previouslink' in the TreeView ... \n";
 139  		        for (my $i=0; $i < $anchors->length; $i++) {
 140  			       	$anchor = $anchors->item($i);
 141  	        		#print $anchor->innerHTML."\n";
 142  		       		if ( $anchor->innerHTML =~ /$Previouslink/ ) {
 143  					print "Clicking on '$Previouslink' ... \n";
 144  	              		  	$anchor->Click;
 145  					last;
 146  				}
 147  		        }
 148  			unshift @TreeViewLinks,$link;
 149  		}
 150  	} 
 151     
 152  	# STEP 3 : Verify the list displayed 
 153  		
 154  	if ($Event eq "DocumentComplete") {    
 155     		if ( @TreeViewLinks == 0 and $IEObject->Document->URL =~ /listeRefPlof.aspx/ ) {
 156  			print "Scenario completed, exiting ...\n";
 157  			$ScenarioCompleted=1;
 158  	   		Win32::OLE->QuitMessageLoop;
 159  		}
 160  	}
 161      
 162  
 163  	# Exit on errors
 164  	    
 165  	Win32::OLE->QuitMessageLoop() if $Event eq "OnQuit" or time() > $WatchDog + 60;
 166      
 167  }

Simple output of date in perl

// Simple output of current date in perl

   1  
   2    my @day_name = ("Sun.","Mon.","Tue.","Wed.","Thu.","Fri.","Sat.");
   3    my ($sec,$min,$hour,$mday,$mon,$year,$wday); 
   4    ($sec,$min,$hour,$mday,$mon,$year,$wday,undef,undef)=localtime(time()); $year+=1900;$mon++;
   5    $report_date=sprintf("%s %04d.%02d.%02d %02d:%02d",$day_name[$wday],$year,$mon,$mday,$hour,$min);
« Newer Snippets
Older Snippets »
Showing 1-4 of 4 total  RSS