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
use strict;
use Net::Ping;
use IO::Socket::INET;

sub isodate() {
        my ($day, $mon, $year, $hour, $min, $sec) = (localtime)[3, 4, 5, 2, 1, 0];
        $mon++; # 0-based index
        $year = $year + 1900;
        my $date = sprintf ("%04i-%02i-%02i %02i\:%02i\:%02i", $year, $mon, $day, $hour, $min, $sec);
        return $date;
}

sub testhost {
       my $p = new Net::Ping("tcp");
       $p->{port_num}=80; 
       my @result = $p -> ping($_[0],2);
       return $result[0];
       }

sub to_dot {
	my $n = shift;
	my @decimal;
	for (1..4) {
		unshift @decimal, $n & 0xFF;
		$n >>= 8;
	}
	return join(".",@decimal);
}

my %dejavu;
open FH,"liste.txt";
while (<FH>) {
	chomp;
	my ($routeur,$mask)=split;
	
	next if $routeur !~ /\d+\.\d+\.\d+\.\d+$/ or $mask !~ /\d+\.\d+\.\d+\.\d+$/;
	
	next if defined($dejavu{$routeur});
	$dejavu{$routeur}=1;
	
	my ($o1,$o2,$o3,$o4) = split /\./,$mask;
	my $mask=$o1*256**3+$o2*256**2+$o3*256+$o4;
	my $num = $mask ^ 0xFFFFFFFF;
	$num--;

	my ($o1,$o2,$o3,$o4) = split /\./,$routeur;
	my $net=$o1*256**3+$o2*256**2+$o3*256+$o4 & $mask;
	
	#print join("|",$routeur,&to_dot($net),$num)."\n";
	
	print "Starting scanning network ".to_dot($net).", router = ".$routeur."\n";
	print "Adresses demarrant de ".to_dot($net+1)." et finissant a ".to_dot($net+$num).".\n";
	for my $i (1..$num) {
		my $host=to_dot($net+$i);
		if ( &testhost($host) ) {
			print "$host is alive\n";
			my $port=80;
			my $sock = new IO::Socket::INET (PeerAddr => $host,
					     PeerPort => $port,
					     Proto => 'tcp');
			if ($sock){
				close $sock;
				print "$port -open on $host\n";
				open OUT,">>webservers.txt";
				print OUT join("|",isodate(),$host,to_dot($net),$routeur)."\n";
				close OUT;
			}	else	{
				print "$port -closed on $host\n";
			}

		} else {
			print "$host is not responding\n";
		}
	}
}


close FH;

Browser automation using perl LWP

// This is a sample code used to measure reports response times on a OAS application.
#!/usr/bin/perl
#
# LWP connection to the Datamart Portal
# Timing of the main reports
#

use strict;
require LWP::UserAgent;

my $ua = LWP::UserAgent->new;

sub isodate() {
        my ($day, $mon, $year, $hour, $min, $sec) = (localtime)[3, 4, 5, 2, 1, 0];
        $mon++; # 0-based index
        $year = $year + 1900;
        my $date = sprintf ("%04i-%02i-%02i %02i\:%02i\:%02i", $year, $mon, $day, $hour, $min, $sec);
        return $date;
}

sub datamart_login {
        my ( $user, $pass ) = @_;
        my $time_begin=time();
        my $url='http://daprd:7782/portal/page?_pageid=37,134413,37_134422&_dad=portal&_schema=PORTAL';
        my $req = HTTP::Request->new( GET => $url );
        my $resp = $ua->request($req);
        my $loginform = $resp->content ;
        if ( $loginform !~ /Entrez votre nom utilisateur/ ) {
                die isodate()." Failed to get the logon page of the Web Site\n";
        } else {
                my $locale="";
                my ($v) = $loginform =~ /NAME=\"v\" value=\"(.+)\"/;
                my ($site2pstoretoken) = $loginform =~ /NAME=\"site2pstoretoken\" value=\"(.+)\"/;
                my ($submiturl) = $loginform =~ /form method=\"POST\" action=\"(.*?)\"/;
                $resp = $ua->post( $submiturl,
                   [
                     ssousername => $user,
                     password => $pass,
                     v => $v,
                     locale => $locale,
                     site2pstoretoken => $site2pstoretoken
                   ],
                );
                $resp = $ua->get($url);
                $resp = $ua->get($url);
                if ( $resp->content !~ /Crit..res de recherche/ ) {
                        die isodate()." Failed to get the main page of Portal\n";
                }
        }
        print join(";",isodate(),"Time to log on the Portal",time()-$time_begin,$url)."\n";
}

sub datamart_testurl {
        my ($label,$url,$expected)=@_;
        my $time_begin=time();
        my $resp;
        $resp = $ua->get($url);
        $resp = $ua->get($url) if $resp->content !~ /$expected/;        # We try two times !
        if ( $resp->content !~ /$expected/ ) {
                print STDERR isodate()." Test Failed on $label. $expected not found in response.\n";
                print STDERR $resp->as_string;
        } else {
                print join(";",isodate(),$label,time()-$time_begin,$url)."\n";
        }
}

$ua->timeout(1200);
$ua->cookie_jar({});
$ua->agent( 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)' );
#push @{ $ua->requests_redirectable }, 'POST';

# >>>> Main code here

datamart_login("xxxx","xxxx");

open FH,"/exploit/scripts/appli/check_datamart.ini" or die "Unable to open check_datamart.ini";
while (<FH>) {
        chomp();
        my ($report,$expected,$url) = split /;/;
        datamart_testurl($report,$url,$expected);
}
close FH;

# <<<< Main code here

Internet Explorer automation using win32::OLE

// Sample code used for one of my client
#!/usr/bin/perl -w

use strict;
use Data::Dumper;
use Win32::OLE qw( EVENTS );

my ($day, $mon, $year, $hour, $min, $sec) = (localtime)[3, 4, 5, 2, 1, 0];
$mon++; # 0-based index
$year = $year + 1900;
my $date = sprintf ("%04i-%02i-%02i %02i\:%02i\:%02i", $year, $mon, $day, $hour, $min, $sec);

my $Disconnect;
my $Menu;
my $TreeView;
my $WatchDog;
my $MenuClicked=0;

my $ScenarioCompleted=0;

my @TreeViewLinks=("Appareillage du B","Branchement Comptage","Branchement individuel");
my $Previouslink=$TreeViewLinks[0];

my $ie = Win32::OLE->new( 'InternetExplorer.Application' ) or die "error starting IE";
$ie->{visible} = 1;

Win32::OLE->Option( Warn => 3 );

$WatchDog=time();
Win32::OLE->WithEvents( $ie, \&Event, 'DWebBrowserEvents2' );
$ie->navigate( 'http://www.xxx.fr' );
Win32::OLE->MessageLoop();
unlink("noemis.err") if -f "noemis.err";
if ( ! $ScenarioCompleted ) {
	open( ERR , ">noemis.err" ); 
	print ERR "Problem executing Noemis scenario, please check www.xxx.fr.\n" ;
	close(ERR);
}
$Disconnect->Click();
Win32::OLE->SpinMessageLoop;

# Maintenance du fichier historique
open ( STATS , "noemis.txt" );
my @lines=<STATS>;
close (STATS);
open( STATS , ">noemis.txt" ); 
for my $line (@lines) {
	my ($datetime) = split ( /;/ , $line );
	my ($h_year,$h_mon) = $datetime =~ /^([0-9]{4})-([0-9]{2})/;
	print STATS $line if ($year*12+$mon) - ($h_year*12+$h_mon) < 2;
}
print STATS join(";",$date,"Noemis Scenario",( time() - $WatchDog ))."\n";
close( STATS );

sleep 2;
Win32::OLE->SpinMessageLoop;
sleep 1;
$ie->Quit();
exit 0;


sub Event {
	my ($Obj,$Event,@Args) = @_;
	my $IEObject = shift @Args;
	print " Event triggered: $Event\n";    

	my ($i,$anchor);
	my $anchors;
    
	# STEP 1 : Find the main menu, login to the web site, find the treeview
	if ($Event eq "DocumentComplete") {    
		print "URL: " . $IEObject->Document->URL . "\n";
		if ( $IEObject->Document->URL eq "http://www.xxx.fr/ident.aspx" ) {
			my $forms = $IEObject->Document->forms;
			my $form = $forms->item(0);
			if ( defined($form->elements("fldNumCli")) ) {
				print "--------------------------------------------\n";
				print "Found the login box, authenticating ...\n";
				print "--------------------------------------------\n";
			    $form->elements("fldNumCli")->{value} = "xxxx";
			    $form->elements("fldUtil")->{value} = "xxx";
			    $form->elements("fldPwd")->{value} = "xxx";
		    	$form->elements("btIdent")->Click();
	    		}
		}
		if ( $IEObject->Document->URL eq "http://www.xxx.fr/menu.aspx" ) {
			print "Found the menu.\n";
			$Menu = $IEObject->Document;
			$anchors = $IEObject->Document->links;
			for (my $i=0; $i < $anchors->length; $i++) {
				$anchor = $anchors->item($i);
				print $anchor->href."\n";
				$Disconnect = $anchor if $anchor->href eq "http://www.xxx.fr/ident.aspx?qs=deconnecter";
			}
	      	}	    
		if ( $IEObject->Document->URL eq "http://www.xxx.fr/client/frameTreeview.aspx" ) {
			print "Found the TreeView.\n";
			$TreeView = $IEObject->Document;
      		}		
	}

	# STEP 2 : Click on the Menu and TreeView links   
	if ($Event eq "DocumentComplete") {    		
	if ( ! $MenuClicked and defined($Menu) ) {
		my $MenuItem = $Menu->getElementById("SM_CLIE_RECH");
		if ( defined($MenuItem) ) { 
			print $MenuItem->ID."\n";
			$MenuItem->Click;
			$MenuClicked = 1;
		}
	}}

	if ( $Event eq "CommandStateChange" or $Event eq "StatusTextChange" ) {
		print Dumper($IEObject);
	}
	if ( @TreeViewLinks != 0 and 
	     defined($TreeView) and 
	     $Event eq "DocumentComplete" 
	) {
		my $link = shift(@TreeViewLinks);
		$anchors = $TreeView->links;
		my $found=0;
		print "Looking for '$link' in the TreeView ... \n";
	        for (my $i=0; $i < $anchors->length; $i++) {
		       	$anchor = $anchors->item($i);
	        	#print $anchor->innerHTML."\n";
		       	if ( $anchor->innerHTML =~ /$link/ ) {
				print "Clicking on '$link' ... \n";
	                	$anchor->Click;
				$found=1;
				$Previouslink=$link;
				last;
			}
	        }
		if ( ! $found ) { 
			# Le TreeView a bugge, on reclique
			sleep 1;
			print "Looking for '$Previouslink' in the TreeView ... \n";
		        for (my $i=0; $i < $anchors->length; $i++) {
			       	$anchor = $anchors->item($i);
	        		#print $anchor->innerHTML."\n";
		       		if ( $anchor->innerHTML =~ /$Previouslink/ ) {
					print "Clicking on '$Previouslink' ... \n";
	              		  	$anchor->Click;
					last;
				}
		        }
			unshift @TreeViewLinks,$link;
		}
	} 
   
	# STEP 3 : Verify the list displayed 
		
	if ($Event eq "DocumentComplete") {    
   		if ( @TreeViewLinks == 0 and $IEObject->Document->URL =~ /listeRefPlof.aspx/ ) {
			print "Scenario completed, exiting ...\n";
			$ScenarioCompleted=1;
	   		Win32::OLE->QuitMessageLoop;
		}
	}
    

	# Exit on errors
	    
	Win32::OLE->QuitMessageLoop() if $Event eq "OnQuit" or time() > $WatchDog + 60;
    
}

Simple output of date in perl

// Simple output of current date in perl

  my @day_name = ("Sun.","Mon.","Tue.","Wed.","Thu.","Fri.","Sat.");
  my ($sec,$min,$hour,$mday,$mon,$year,$wday); 
  ($sec,$min,$hour,$mday,$mon,$year,$wday,undef,undef)=localtime(time()); $year+=1900;$mon++;
  $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