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-3 of 3 total  RSS 

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  }

ASP Page listing and making changes to AD accounts

// Used for automated AD account migration
   1  
   2  <HTML><HEAD><TITLE>Workstation User Account migration</TITLE>
   3  <META http-equiv=Content-Type content="text/html; charset=iso-8859-1"><LINK 
   4  href="files/v2006.css" type=text/css rel=stylesheet>
   5  <BODY leftMargin=0 topMargin=30 marginwidth="0" marginheight="0">
   6  <CENTER>
   7  <%
   8  ' ------------------------------------------------------------------------
   9  Const ADS_PROPERTY_CLEAR = 1
  10  
  11  Const SOURCE_OU="ou=NT Users,ou=NT,dc=fr,dc=erm,dc=int"
  12  Const TARGET_OU="ou=SUPPORT SERVICES,dc=fr,dc=erm,dc=int"
  13  
  14  Const HOMES_PATH="\\frsrvfil0001\USERS\"
  15  Const PROFILES_PATH="\\frsrvfil0001\PROFILES\"
  16  
  17  Const ADMIN_HOMES_PATH_SOURCE="\\frsrvfil0001\U$\NT\"
  18  Const ADMIN_PROFILES_PATH_SOURCE="\\frsrvfil0001\P$\NT\"
  19  Const ADMIN_HOMES_PATH_DEST="\\frsrvfil0001\U$\"
  20  Const ADMIN_PROFILES_PATH_DEST="\\frsrvfil0001\P$\"
  21  
  22  Const SCRIPT_NAME="ntuser_to_xp.asp"
  23  
  24  Dim State
  25  State="Init"
  26  Dim OU, Member
  27   
  28  If Request.QueryString("login") <> "" Then
  29  		' Affichage formulaire pour modif du compte
  30  		State="Info"
  31  End If
  32  If Request.Form("login") <> "" Then
  33  		' On a cliqué sur OK pour valider le formulaire
  34  		State="Modify"
  35  End If
  36  ' ------------------------------------------------------------------------
  37  %>
  38  <TABLE cellSpacing=0 cellPadding=1 width=500 align=center bgColor=#26333e 
  39  border=0>
  40    <TBODY>
  41    <TR>
  42      <TD>
  43        <TABLE cellSpacing=0 cellPadding=1 width=500 align=center border=0>
  44          <TBODY>
  45          <TR bgColor=#f0f3f5>
  46            <TD width=160 valign="top"><IMG height=116 src="files/man_portable.jpg" 
  47              width=160> </TD>
  48            <TD width=302 bgColor=#e5ebef>
  49  
  50  <%
  51  	If State="Init" Then
  52  	'-----------------------------------------------------------------------------------
  53  	' Listing of the NT Users
  54  	'-----------------------------------------------------------------------------------
  55  %>          
  56  
  57              <TABLE cellSpacing=4 cellPadding=4 width="100%" align=center 
  58              border=0>
  59                <TBODY>
  60                <TR>
  61                  <TD class=medium colSpan=3 height=22>
  62                      <%
  63                      'Response.Write(SOURCE_OU & "<BR>") 
  64                      %>
  65  					Please select the NT 4.0 Workstation user account to migrate
  66                  </TD></TR>
  67                  
  68                <TR>
  69                  <TD class=td11 height=22>
  70                                    <%
  71                    Set OU = GetObject("LDAP://" & SOURCE_OU)
  72                    OU.Filter = Array("user")
  73      	          For Each Member In OU
  74      	          		' Bug with the SMS Account ??
  75      	          		If Member.Name <> "CN=SMSService" Then 
  76      	          		If Member.AccountDisabled = 0 Then
  77  	    	                Response.Write("<A HREF=""" & SCRIPT_NAME & "?login=" & Server.URLEncode(Member.Name) & """>" & Member.FullName & "</A><BR>")
  78  	    	            End If
  79  	    	            End If 
  80              	  Next      
  81                    
  82                    %>
  83  
  84                  </TD>
  85                  </TR>
  86                  
  87                  </TBODY></TABLE>
  88  
  89  <%
  90  End If
  91  %>                
  92                  
  93  <%
  94  	If State="Info" Then
  95  	'-----------------------------------------------------------------------------------
  96  	' Information page about the NT Users
  97  	'-----------------------------------------------------------------------------------
  98  %>          
  99  			<FORM method=post>
 100  
 101              <TABLE cellSpacing=4 cellPadding=4 width="100%" align=center 
 102              border=0>
 103                <TBODY>
 104                <TR>
 105                  <TD class=medium colSpan=2 height=22>
 106                   	<%
 107                   	Response.Write("Windows NT 4.0 User Account Migration")
 108                      %>
 109  					
 110                  </TD></TR>
 111                 
 112                    <%
 113                    Sub TabRow(v1,v2)
 114                    		Response.Write("<TR class=td11 height=16><TD><B>" & v1 & "</B>")
 115                    		Response.Write("<TD>" & v2 & "</TD>")
 116                    		Response.Write("</TD></TR>")
 117                    End Sub
 118                    Set Member = GetObject("LDAP://" & Request.QueryString("login") & "," & SOURCE_OU)
 119  
 120                    TabRow "User Name",Member.FullName
 121                    TabRow "NT Login",Member.sAMAccountName
 122  				  TabRow "Login Script", Member.LoginScript & " (to delete)"
 123  				  TabRow "Profile Path", Member.Profile
 124  				  TabRow "New Path",PROFILES_PATH & Member.sAMAccountName
 125  				  TabRow "Home Folder", Member.HomeDirectory
 126  				  TabRow "New Path",HOMES_PATH & Member.sAMAccountName
 127  				  
 128  				  ' Liste des OU dans SUPPORT SERVICES
 129   				  Dim OUSuppServices, Entity, BoxList
 130   				  Set OUSuppServices=GetObject("LDAP://" & TARGET_OU)
 131  				  OUSuppServices.Filter = Array("organizationalUnit")
 132  				  BoxList="<SELECT NAME=""entity"">"
 133  				  For Each Entity in OUSuppServices
 134  				  	BoxList= BoxList & "<OPTION VALUE=""" & Entity.Name & """>" & Mid(Entity.Name,4) & "</OPTION>"
 135  				  Next
 136  				  BoxList=BoxList & "</SELECT>"
 137  				  TabRow "Organizational Unit",BoxList
 138                                      
 139                    %>
 140  
 141                  
 142                  </TBODY></TABLE>
 143                  <BR>
 144                  <INPUT name=login type=hidden value=<% Response.Write(Member.sAMAccountName) %> >
 145                  <INPUT type=image height=18 alt="GO !" width=15 src="files/submit.gif" value=login border=0 name=ok>
 146                  &nbspCliquer ici pour migrer ce compte.<BR><BR>
 147                  ATTENTION, l'utilisateur ne doit pas être connecté ! 
 148                  <% Response.Write("<BR><BR><A HREF=""" & SCRIPT_NAME & """>" & "Cliquer ICI pour annuler" & "</A><BR>") %>
 149                  </FORM>
 150  
 151  <%
 152  End If
 153  %>                
 154  
 155  <%
 156  
 157  	If State="Modify" Then
 158  	'-----------------------------------------------------------------------------------
 159  	' Migration of the NT Users
 160  	'-----------------------------------------------------------------------------------
 161  Sub dirMoveTree(source, dest)
 162  	Response.Write "Deplacement de <B>" & source & " vers " & dest & "</B><BR>"
 163  	Dim Folder,File,SubFolder
 164  	set Folder=fso.GetFolder(source)
 165  	For Each File In Folder.Files
 166  	      Response.Write File.Name & " File -> " & dest & "<BR>"
 167  	      file.move dest & "\"
 168  	Next
 169  	For Each SubFolder In Folder.SubFolders
 170  	      Response.Write SubFolder.Name & " Folder -> " & dest & "<BR>"
 171  	      SubFolder.move dest & "\"
 172  	Next
 173  End Sub
 174  
 175  %>          
 176  <CENTER>
 177  Windows NT 4.0 User Account Migration<BR><BR>
 178  <%
 179  
 180  ' Modification des proprietes l'utilisateur dans AD
 181  Set Member = GetObject("LDAP://" & Request.QueryString("login") & "," & SOURCE_OU)
 182  
 183  ' ADS_PROPERTY_CLEAR
 184  Member.PutEx 1, "scriptPath", 0
 185  Member.SetInfo
 186  
 187  Member.Put "profilePath", PROFILES_PATH & Member.sAMAccountName
 188  Member.Put "homeDirectory", HOMES_PATH & Member.sAMAccountName
 189  ' 
 190  Member.SetInfo
 191  ' 
 192  Response.Write("Utilisateur <B>" & Member.sAMAccountName & "</B> Modifié dans AD<BR><BR>")
 193  
 194  ' Deplacement dans le bon conteneur
 195  Set OU = GetObject("LDAP://" & "OU=Users," & Request.Form("entity") & "," & TARGET_OU)
 196  OU.MoveHere "LDAP://" & Request.QueryString("login") & "," & SOURCE_OU, Request.QueryString("login")
 197  Response.Write("Utilisateur <B>" & "LDAP://" & Request.QueryString("login") & "," & SOURCE_OU & "</B> Deplacé dans " & "LDAP://" & "OU=Users," & Request.Form("entity") & "," & TARGET_OU & "<BR><BR>")
 198  
 199  DIM fso, File, Folder, SubFolder
 200  Set fso = CreateObject("Scripting.FileSystemObject")
 201  
 202  ' Creation des repertoires cible
 203  
 204  fso.CreateFolder(ADMIN_HOMES_PATH_DEST & Request.Form("login"))
 205  fso.CreateFolder(ADMIN_PROFILES_PATH_DEST & Request.Form("login"))
 206  
 207  ' Deplacement des données
 208  
 209  dirMoveTree ADMIN_HOMES_PATH_SOURCE & Request.Form("login"),ADMIN_HOMES_PATH_DEST & Request.Form("login")
 210  dirMoveTree ADMIN_PROFILES_PATH_SOURCE & Request.Form("login"),ADMIN_PROFILES_PATH_DEST & Request.Form("login")
 211  
 212  ' Applications des ACLs, en arriere plan car ca peut etre long !
 213  Response.Write("<BR>Creation du script d'application des ACLs C:\Inetpub\wwwroot\techcity\xcacls_" & Request.Form("login") & ".cmd<BR><BR>")
 214  Set server_shell = Server.CreateObject("wscript.shell")
 215  
 216  server_shell.Run "cmd /c echo echo Excecution Cacls >C:\Inetpub\wwwroot\techcity\xcacls_" & Request.Form("login") & ".cmd 2>&1",,1
 217  server_shell.Run "cmd /c echo xcacls.exe """ & ADMIN_HOMES_PATH_DEST & Request.Form("login") & """ /T /C /G SYSTEM:F ADMINISTRATORS:F FR-ERM\" & Request.Form("login") & ":C /Y >>C:\Inetpub\wwwroot\techcity\xcacls_" & Request.Form("login") & ".cmd 2>&1",,1
 218  server_shell.Run "cmd /c echo xcacls.exe """ & ADMIN_PROFILES_PATH_DEST & Request.Form("login") & """ /T /C /G SYSTEM:F ADMINISTRATORS:F FR-ERM\" & Request.Form("login") & ":F /Y >>C:\Inetpub\wwwroot\techcity\xcacls_" & Request.Form("login") & ".cmd 2>&1",,1
 219  
 220  ' server_shell.Run "C:\Inetpub\wwwroot\techcity\xcacls.cmd >C:\Inetpub\wwwroot\techcity\xcacls.log 2>&1",,1
 221  Response.Write("<BR>Les ACLs seront appliquee dans 5 min (scheduled)...<BR><BR>")
 222  Response.Write("Attendre egalement la fin de replication de AD ...<BR><BR>")
 223  
 224  Response.Write("<BR>Terminé !<BR>")
 225  
 226  %>
 227  <% Response.Write("<BR><BR><A HREF=""" & SCRIPT_NAME & """>" & "Cliquer ICI pour quitter" & "</A><BR>") %>
 228  </CENTER>
 229  <%
 230  End If
 231  %>                
 232  
 233  
 234                </TD></TR>            
 235                  
 236                  </TBODY></TABLE></TD></TR>
 237                          
 238                  
 239  </TBODY></TABLE></CENTER></BODY></HTML>
 240  

Simple ASP page to reset passwords

// This page allows to reset an AD account password.
   1  
   2  <HTML><HEAD><TITLE>Reinitialisation de mot de passe</TITLE>
   3  <META http-equiv=Content-Type content="text/html; charset=iso-8859-1"><LINK 
   4  href="files/v2006.css" type=text/css rel=stylesheet>
   5  <BODY leftMargin=0 topMargin=30 marginwidth="0" marginheight="0">
   6  <FORM method=post>
   7  <CENTER>
   8  <TABLE cellSpacing=0 cellPadding=1 width=500 align=center bgColor=#26333e 
   9  border=0>
  10    <TBODY>
  11    <TR>
  12      <TD>
  13        <TABLE cellSpacing=0 cellPadding=1 width=500 align=center border=0>
  14          <TBODY>
  15          <TR bgColor=#f0f3f5>
  16            <TD width=160><IMG height=116 src="files/man_portable.jpg" 
  17              width=160> </TD>
  18            <TD width=302 bgColor=#e5ebef>
  19              <TABLE cellSpacing=4 cellPadding=4 width="100%" align=center 
  20              border=0>
  21                <TBODY>
  22                <TR>
  23                  <TD class=medium colSpan=3 height=22>
  24                  <%
  25                  If Request.Form("login") = "" Then
  26                  	Response.Write("<B>Saisir le compte à reinitialiser</B>")
  27                  Else
  28                      Dim Group, Member, Domain, UserFound
  29                      ' 
  30                      Domain ="FR-ERM"
  31                      '
  32                      UserFound=0
  33                      
  34  	                Set Group = GetObject("WinNT://" & Domain & "/Domain Users")
  35      	            For Each Member In Group.Members
  36      	            	' Response.Write(Member.Name & "<BR>")
  37          	        	If UCase(Member.Name) = UCase(Request.Form("login")) Then
  38          	        		UserFound=1
  39          	        		If Member.AccountDisabled Then 
  40          	        			Response.Write(" " & Request.Form("login") &" est un compte desactive</B>")
  41          	        			Exit For
  42          	        		Else
  43          	        			' Essai de reinit de mot de passe
  44          	        			Dim res
  45          	        			res=Member.SetPassword(Request.Form("pass"))
  46          	        			'Member.Put "pwdLastSet", CLng(0)
  47          	        			Member.Put "PasswordExpired", 1
  48  								Member.SetInfo
  49          	        			Response.Write("<B>L'utilisateur "& Request.Form("login") & " a changé de mot de passe !<BR><BR></B>Il devra changer de mot de passe au prochain login.")
  50          	        			Exit For
  51          	        		End If
  52          	        	End If 
  53              	    Next      
  54         	        	If UserFound = 0 Then
  55         	        		Response.Write(Request.Form("login") &" non trouvé dans le domaine "& Domain)
  56         	        	End If           	            	
  57                  	
  58                  End If
  59                  %>
  60                
  61                  </TD></TR>
  62                <TR>
  63                  <TD class=td11 width="1%" height=22>Identifiant
  64                 
  65                  </TD>
  66                  <TD class=td11 colSpan=2>Nouveau mot de passe</TD></TR>
  67                <TR>
  68                  <TD width="25%"><INPUT maxLength=20 name=login>
  69   
  70                  </TD>
  71                  <TD width="20%"><INPUT type=password maxLength=10 size=10 
  72                    name=pass> </TD>
  73                  <TD><INPUT type=image height=18 alt="Reset !" width=15 
  74                    src="files/submit.gif" value=login border=0 name=ok> 
  75                  </TD></TR></TBODY></TABLE></TD></TR></TBODY></TABLE></TD></TR></TBODY></TABLE></CENTER></FORM></BODY></HTML>
« Newer Snippets
Older Snippets »
Showing 1-3 of 3 total  RSS