Monday, December 20, 2010

Perl Example

#!/bin/perl
#realsecure to agentservicename and ISS to aISS
$startCommand = "/etc/init.d/agentservicename start";
$stopCommand = "/etc/init.d/agentservicename stop";
# THE ONLY LINES THAT SHOULD NEED TO BE EDITED IN THIS SCRIPT ARE THE THREE ABOVE
# THIS SCRIPT SHOULD AUTOMATICALLY DETECT ALL OTHER SENSOR SETTINGS
# THE FIRST VALUE ABOVE SHOULD BE "#!" FOLLOWED BY THE VALUE OF "which perl" FROM THE COMMAND LINE
# THE SECOND VALUE ABOVE SHOULD BE THE START COMMAND FOR THE APPLICABLE PLATFORM
# THE THIRD VALUE ABOVE SHOULD BE THE STOP COMMAND FOR THE APPLICABLE PLATFORM
print "\nResetting aISS sensors for SiteProtector connectivity...\n\n";
# STOPPING THE aISSDAEMON SERVICE
$adjustedStop = "|" . $stopCommand;
open STOP, $adjustedStop;
# WAITING UNTIL THE aISSDAEMON SERVICE IS NO LONGER RUNNING
# THIS IS DONE BY CHECKING ALL ACTIVE SERVICES AND VERIFYING THE aISSDaemon SERVICE IS GONE
$stopWait = 0;
open(PS_F, "ps -ef|");
        while ($stopWait == 0) {
                $stillRunning = 0;
                while (<PS_F>) {
                        (@ps) = split;
                        foreach(@ps) {
                                if ($_ =~ /aISSDaemon/) {
                                        $stillRunning = 1;
#                                       print "aISSDaemon still running...\n";
                                }
                        }
                }
                if ($stillRunning == 0) {
                        $stopWait = 1;
                }
        }
close(PS_F);
close (STOP);
print "\n";
# OPEN CRYPT.POLICY AND READ IN ALL LINES, SET TO @CRYPT ARRAY.
open(INFILE,  "/opt/aISS/aISSDaemon/crypt.policy") or die "Can't open crypt.policy file: $!";
@crypt = <INFILE>;
$cryptReset = 0;
print "Allowing first connection in crypt.policy:  ";
# RESET ALLOW FIRST CONNECTION VALUE TO 1 WHEN STRING MATCH IS FOUND
foreach(@crypt) {
#       print $_;
        if ($_ =~ /allowfirst/) {
                $_ = "allowfirstconnection      =L      1;\n";
                print "Done\n";
                $cryptReset = 1;
        }
#       print $_, "\n";
}
# IF THERE IS NO STRING MATCH FOR ALLOW FIRST CONNECTION, ADD IT TO THE PROPER PLACE IN THE FILE
if ($cryptReset == 0) {
        foreach(@crypt) {
#               print $_;
                if ($_ =~ /authent/) {
                        $_ = $_ . "allowfirstconnection      =L      1;\n";
                        print "MaISSing...Added\n";
                }
#       print $_, "\n";
        }
}
close(INFILE);
# OPEN CRYPT.POLICY FOR WRITING AND SUBMIT NEW VALUES
open(OUTFILE, ">/opt/aISS/aISSDaemon/crypt.policy") or die "Can't open crypt.policy file: $!";
foreach(@crypt) {
        print OUTFILE $_;
#       print $_, "\n";
}
close(OUTFILE);
# OPEN aISSDAEMON.POLICY AND READ IN ALL LINES, SET TO @DAEMON ARRAY.
$sensorCount = 0;
$masterCount = 0;
open(INFILE,  "/opt/aISS/aISSDaemon/aISSDaemon.policy") or die "Can't open aISSDaemon.policy file: $!";
@daemon = <INFILE>;
# PERFORM LINE BY LINE CHECKS ON @DAEMON ARRAY AND PERFORM FUNCTIONS BELOW
foreach(@daemon) {
#       print $_;
# RESET MASTER CONSOLE STATUS FOR EACH OCCURRENCE IN THE ARRAY
        if ($_ =~ /master_console/) {
                $_ = "master_console  =S      ;\n";
                $masterCount = $masterCount + 1;
        }
# SET ELEMENTS OF @SENSORLOC ARRAY TO PATHS IN POLICY PATH ENTRIES
        if ($_ =~ /policy_path/) {
# THIS IS THE TRICKY PART, THE STRING BELOW SEARCHES FOR...
# NON-WHITESPACE --> WHITESPACE --> NON-WHITESPACE --> WHITESPACE --> POLICY PATH --> SEMICOLON
# THE PARENTHESES AROUND THE [\S]+ SET THE VALUE OF $1 TO THAT VALUE WHICH IS...
# THE THIRD OCCURRENCE OF NON-WHITESPACE (FIRST CHAR OF THE PATH) UP TO THE SEMICOLON (LAST CHAR OF THE PATH)
                if ($_ =~ /[\S]+[\s]+[\S]+[\s]+([\S]+)+[;]/) {
                        $sensorLoc[$sensorCount] = $1;
                        $sensorCount = $sensorCount + 1;
                        print "Sensor #", $sensorCount, " found at path:  -->", $1, "<--\n";
                }
        }
#       print $_, "\n";
}
close(INFILE);
print "Resetting ", $masterCount, " occurrences of master status:  Done\n";
# DELETE ALL PUBLIC KEYS IN ALL PATHS LISTED IN @SENSORLOC ARRAY
$feedbackCount = 1;
foreach(@sensorLoc) {
        print "Deleting existing Certicom Keys on Sensor #", $feedbackCount, ":  ";
        $dirTemp = $_ . "Keys/CerticomNRA";
#       print $dirTemp , "\n";
        chdir ($dirTemp);
        @filelist = glob("*");
#       print @filelist, "\n";
        unlink glob("*.PubKey");
        @filelist = glob("*");
#       print @filelist, "\n";
        print "Done\n";
        print "Deleting existing RSA Keys on Sensor #", $feedbackCount, ":  ";
        $dirTemp = $_ . "Keys/RSA";
#       print $dirTemp , "\n";
        chdir ($dirTemp);
        @filelist = glob("*");
#       print @filelist, "\n";
        unlink glob("*.PubKey");
        @filelist = glob("*");
#       print @filelist, "\n";
        print "Done\n";
        $feedbackCount = $feedbackCount + 1;
}
# OPEN aISSDAEMON.POLICY FOR WRITING AND SUBMIT NEW VALUES
open(OUTFILE, ">/opt/aISS/aISSDaemon/aISSDaemon.policy") or die "Can't open aISSDaemon.policy file: $!";
foreach(@daemon) {
        print OUTFILE $_;
#       print $_, "\n";
}
close(OUTFILE);
print "\n";
# RESTARTING THE aISSDaemon SERVICE
$adjustedStart = "|" . $startCommand;
open START, $adjustedStart;
close(START);
print "\nAll aISS Sensors have been reset for SP connectivity.\n\n";

Sunday, November 21, 2010

Recovery

' Recovery Scenario example
Browser("Internet Explorer cannot").Page("Internet Explorer cannot").WebButton("Diagnose Connection Problems").Click
Browser("Internet Explorer cannot").Page("Internet Explorer cannot").WebButton("Diagnose Connection Problems");
Recovery.Enabled=True
Recovery.Activate
wait(1)

'MyCurrentStatus=Recovery.Enabled
''msgbox MyCurrentStatus
'If Not( MyCurrentStatus ) Then
'Recovery.Enabled=True
'End If
'Recovery.Activate
'Recovery = MyCurrentStatus
'msgbox "helo"

This below example will retrieve specified table cell data

' This below example will retrieve specified table cell data
Set oDesc = Description.Create
'oDesc("innerText").Value = "one.*"
oDesc("micClass").Value = "WebTable"
'oDesc("innerText").Value  = True
Set allTables = Browser("Browser").Page("Page").ChildObjects(oDesc)
msgbox allTables.Count
For i=0 to allTables.Count-1
 'msgbox allTables.item(i).ToString()

 If i=2Then
  'msgbox "I value is "&i
  Set des = Description.Create
  des("outertext").Value = "one.*"
  des("outertext").RegularExpression = true
  val = Browser("Browser").Page("Page").WebTable(des).ColumnCount(i)
  msgbox "Coulmn Count is "&val
  celldata = Browser("Browser").Page("Page").WebTable(des).GetCellData(1,i)
  msgbox celldata
  msgbox Browser("Browser").Page("Page").WebTable(des).RowCount
 
 End If
Next
'msgbox objPro.RowCount  ' displays the no. of rows present in a web table
'msgbox objPro.ColumnCount(1) ' displays number of columns in the first row
'msgbox objPro.GetCellData(2,1)
'

' ///////////////////////////////////////////
'Set oDesc = Description.Create
''oDesc("micclass").value = "webbutton"    'this statement working, returned  1
'oDesc("micclass").Value = "webtable"
'oDesc("micclass").RegularExpression = True
'set obj = Browser("Browser").Page("Page").ChildObjects(oDesc)
'
''this loop displays only 1,1 info. it  wont displays the table name or properties
''For i=0 to obj.count-1
'' msgbox obj.item(i).ToString() 
''Next
'
'msgbox "Total webtables " &obj.Count
'' when there was static tables and independent table, means not nested table. For nested table this index will not work
''Set objPro = Browser("Browser").Page("Page").WebTable("index := 0")
'
'' working to identify , when there were nested tables
'Set objPro = Browser("Browser").Page("Page").WebTable("index := 1")
'
'msgbox objPro.RowCount  ' displays the no. of rows present in a web table
'msgbox objPro.ColumnCount(1) ' displays number of columns in the first row
'msgbox objPro.GetCellData(2,1)
'
''set res = Browser("Browser").Page("Page").Webtable("").GetTOProperties
'''msgbox res.count
''For k=0 to  res.count-1
'' msgbox res(k).Name
'' msgbox res(k).value
''Next

Dynamically reading Frames and its contents

' C:\Perl\html\index.html
Dim frame(2)
frame(1) = "PerlDoc"
frame(0) = "TOC"
On Error Resume Next
For i=0 to ubound(frame)-1
 'msgbox frame(i)
     If Browser("ActivePerl User Guide").Page("ActivePerl User Guide").Frame(frame(i)).Link("ASPN Perl").Exist Then
   msgbox frame(i)
   msgbox "yes"
   If Err.Number <= 0 Then
     Browser("ActivePerl User Guide").Page("ActivePerl User Guide").Frame(frame(i)).Link("ASPN Perl").Click
     Else
     msgbox frame(i) 
   End If
 
  End If
Next

'Browser("ActivePerl User Guide").Page("ActivePerl User Guide").Frame("PerlDoc").Link("ASPN Perl").Click
Browser("ActivePerl User Guide").Page("ActivePerl User Guide").Frame("PerlDoc").Link("ASPN Perl")
'Browser("Internet Explorer cannot").Page("Internet Explorer cannot").Sync
'Browser("Internet Explorer cannot").CloseAllTabs

ChildObjects - Frames,Dynamic Array

'http://localhost/sqlitemanager/
'Browser("WAMP5 Homepage").Page("WAMP5 Homepage").Link("phpinfo( )").Click @@ hightlight id_;_Browser("WAMP5 Homepage").Page("WAMP5 Homepage").Link("phpinfo( )")_;_script infofile_;_ZIP::ssf7.xml_;_
'Browser("WAMP5 Homepage").Page("WAMP5 Homepage").Link("SQLitemanager 1.2.0").Click @@ hightlight id_;_Browser("WAMP5 Homepage").Page("WAMP5 Homepage").Link("SQLitemanager 1.2.0")_;_script infofile_;_ZIP::ssf8.xml_;_
'Browser("WAMP5 Homepage").Page("SQLiteManager").Frame("main").WebCheckBox("uploadDB").Set "ON" @@ hightlight id_;_Browser("WAMP5 Homepage").Page("SQLiteManager").Frame("main").WebCheckBox("uploadDB")_;_script infofile_;_ZIP::ssf9.xml_;_
'Browser("WAMP5 Homepage").Page("SQLiteManager").Frame("main").WebCheckBox("uploadDB").Set "OFF" @@ hightlight id_;_Browser("WAMP5 Homepage").Page("SQLiteManager").Frame("main").WebCheckBox("uploadDB")_;_script infofile_;_ZIP::ssf10.xml_;_
'Dynamic Arrays
Dim dynamicArray()
Set oDesc = Description.Create
oDesc("micclass").Value = "Frame"
set cObj = Browser("WAMP5 Homepage").Page("SQLiteManager").ChildObjects(oDesc)
'msgbox cObj.Count
ReDim dynamicArray(cObj.Count)
' below for loop will convert  as below :
' from =  [ welcome ] link
'  to = welcome
For i=0 to cObj.Count -1
 childObjVal = cObj.item(i).ToString()  ' msgbox childObjVal
 startPos = Instr(1,childObjVal,"[")
 newVal = mid(childObjVal,startPos+1,len(childObjVal))
 endPos = instr(1,newVal,"]")
 endVal = mid(newVal,1,endPos-1)
    dynamicArray(i) = trim(endVal)  ' msgbox dynamicArray(i)
Next
'msgbox ubound(dynamicArray)
' below for loop is used click left side frames specific link
For j=0 to ubound(dynamicArray)-1
    strArray = dynamicArray(j)
If  strArray = "left" Then
    Set oDes = Description.Create
 oDes("micclass").Value = "Link"
 set childLinks = Browser("WAMP5 Homepage").Page("SQLiteManager").Frame(strArray).ChildObjects(oDes)  ' Browser("WAMP5 Homepage").Page("SQLiteManager").Frame("left").Link("Test").Click @@ hightlight id_;_Browser("WAMP5 Homepage").Page("SQLiteManager").Frame("main").WebCheckBox("uploadDB")_;_script infofile_;_ZIP::ssf9.xml_;_
     For k=0 to childLinks.Count -1
  childLinksVal = childLinks.item(k).ToString()    ' msgbox childLinksVal
  startPos = Instr(1,childLinksVal,"[")
  newVal = mid(childLinksVal,startPos+1,len(childLinksVal))
  endPos = instr(1,newVal,"]")
  endVal =  mid(newVal,1,endPos-1)   'dynamicArray(i) = trim(endVal)
  endVal = trim(endVal)
  msgbox trim(endVal)
  If endVal = "Test" Then
   Browser("WAMP5 Homepage").Page("SQLiteManager").Frame(strArray).Link(endVal).Click
   msgbox "Test is clicked"
  End If
 Next
End If
Next
' How to find co-ordinates of any text in the application
'l = 0
't = 0
'r = 0
'b = 0
'result = Window("Mozilla Firefox").WinObject("MozillaWindowClass").GetTextLocation("test123",l,t,r,b) @@ hightlight id_;_2164128_;_script infofile_;_ZIP::ssf1.xml_;_
'If result Then @@ hightlight id_;_460284_;_script infofile_;_ZIP::ssf2.xml_;_
' MsgBox "Text found. Coordinates:" & l & "," & t & "," & r & "," & b
'End If

' GetTOProperties example
'set objPro = Window("Mozilla Firefox").WinObject("MozillaWindowClass").GetTOProperties
'msgbox objPro.Count
'For i=0 to objPro.count-1
' 'msgbox objPro(i).Name
'If objPro(i).Name = "text" Then
' msgbox objPro(i).Name ' property name
'End If
'Next

ChildObjects - Click desired link

' Browser("iTKO LISA Functional Testing").Page("iTKO LISA Functional Testing").Link("Key Features").Click
Set oDesc = Description.Create()
    oDesc("micclass").Value = "Link"
 'oDesc("Class Name").Value = "Link"   
'Set Lists = Browser("iTKO LISA Functional Testing").Page("iTKO LISA Functional Testing").ChildObjects(oDesc)
Set Lists = Browser("iTKO LISA Functional Testing").Page("WAMP5 Homepage").ChildObjects(oDesc)
'Set Lists = Browser("iTKO LISA Functional Testing").Page("Internet Explorer cannot").ChildObjects(oDesc)
    NumberOfLists = Lists.Count()
 'msgbox NumberOfLists
 bVal = ""
For i = 0 To NumberOfLists - 1
    sVal = Lists.item(i).ToString()
 'msgbox sVal  ' return value like - [ xyz ] link
 startPos = Instr(1,sVal,"[")
 newVal = mid(sVal,startPos+1,len(sVal))
 endPos = instr(1,newVal,"]")
 endVal = mid(newVal,1,endPos-1)
 msgbox endVal
Next
'Browser("iTKO LISA Functional Testing").Page("Internet Explorer cannot").Link("More information").Click
'If endVal="test123" Then
'  msgbox endVal
'  Reporter.ReportEvent micPass,"Match Found","Success - Found the match"
'  Else
'   'Reporter.ReportEvent micFail,"Match Not Found","Fail - Match not found"
'    End If

Import Data Shet - example

' Import Data Sheet
DataTable.Import "C:/perldbtesting.xls"
rCount = DataTable.GetRowCount
msgbox rCount
For i=1 to rCount Step 1
 DataTable.SetCurrentRow(i)
  sno = DataTable.Value("sno",dtGlobalSheet)
  name_ = DataTable.Value("name",dtGlobalSheet)
       msgbox sno
    msgbox name_
Next
DataTable.DeleteSheet "Action1"
DataTable.AddSheet("newsheet").AddParameter "newParam","Added new sheet & and then added new column param and value is filled"
oldVal = DataTable.Value ("newParam","newsheet")
msgbox oldVal

FSO Examples

Set fso = CreateObject ("Scripting.FileSystemObject")
If fso.FolderExists ("C:\parent") Then
 ' fso.GetParentFolderName ("C:\parent")            '- displays C:/
 'msgbox fso.GetFolder("C:\parent").IsRootFolder       ' false
     'icount = fso.GetFolder("C:\parent").SubFolders.Count     ' returns count
    Set f = fso.GetFolder("c:\parent")
    Set sf = f.SubFolders
  For Each f1 in sf
   s = s & f1.name
   s = s & ";"
  Next
   ShowFolderList = s
End If
  msgbox ShowFolderList
  ' lst = Array(10)    
  lst = split (ShowFolderList, ";")
  icount = ubound(lst)
  For i=0 to icount-1 step 1
   msgbox lst(i)
  Next
 
  'msgbox arr()
'set obj = CreateObject ("WScript.Shell")
'set oExec = obj.Exec ("perl c:\Perl\eg\example.pl")
'msgbox oExec.Status
'If  oExec.Status = 0 Then
' Reporter.ReportEvent micWarning, perlscript, "Success"
' Else
' Reporter.ReportEvent micWarning, perlscript, "Fail"
'End If
'Set fso = CreateObject ("Scripting.FileSystemObject")
'If  fso.FolderExists ("C:\QTPPractice")  Then
' msgbox "Folder Already Exists"
' Reporter.ReportEvent micWarning, FolderExits, "Folder Already Exists"
'Else
'  fso.CreateFolder ("C:\QTPPractice")
'       '  set fileobj = fso.CreateTextFile ("C:\QTPPractice\textfile.txt", ForWriting, True)
'  set fileobj = fso.CreateTextFile ("C:\QTPPractice\textfile.txt")
'  msgbox "Folder and File Created"
'  Reporter.ReportEvent micPass, FolderExits, "Folder and File Created"
'End If

WMI examples

'Set Obj = CreateObject("WScript.Shell")
' val = Obj.Run ("net user rupakala pa$$w0rd /add") -- will execute at command prompt, as background process
'val = Obj.Run ("cmd /K perl c:/Perl/eg/example.pl >c:/testfile.txt")     ' output will be written into testfile.txt
'msgbox val ' returns 0
'Obj.CreateShortcut "C:\Users\Administrator\Desktop\aaaaa.lnk"
' msgbox Obj.CurrentDirectory    '  -----displays current directory path of  script
'set WshSysEnv = Obj.Environment("SYSTEM")
'msgbox WshSysEnv.Item("OS")
'set exe = Obj.Exec ("notepad.exe")
' --- WMI  examples
'Set LoginProfiles = GetObject("winmgmts:").InstancesOf ("Win32_NetworkLoginProfile")
'   For each Profile in LoginProfiles
'     msgbox Profile.Name
'     'msgbox Profile.LogonName
'   next
Set net = CreateObject("WScript.Network")   
' net.MapNetworkDrive "P:", "file://pc/public%22,%22True%22,%22Administrator",""
'msgbox net.ComputerName
'msgbox net.UserName
Set oDrives = net.EnumNetworkDrives()
msgbox oDrives.Count
        For i = 0 to oDrives.Count - 1 Step 2
          msgbox "Drive " & oDrives.Item(i) & " = " & oDrives.Item(i+1)
         Next

Wednesday, October 20, 2010

Switching Service Accounts to Local Service

Changes the service account to LocalService for any services running under the hypothetical service account Netsvc.

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colServices = objWMIService.ExecQuery _
    ("Select * from Win32_Service")
For each objService in colServices
    If objService.StartName = ".\netsvc" Then
        errServiceChange = objService.Change _
        ( , , , , , , "NT AUTHORITY\LocalService" , "") 
    End If
Next

Stopping Services Running Under a Specific Account

Stops all services running under the hypothetical service account Netsvc.

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colServices = objWMIService.ExecQuery _
    ("Select * from win32_Service")
For each objService in colServices
    If objService.StartName = ".\netsvc" Then
        errReturnCode = objService.StopService()
    End If
Next

Stopping a Service and Its Dependents

Stops the NetDDE service and all its dependent services.

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colServiceList = objWMIService.ExecQuery("Associators of " _
   & "{Win32_Service.Name='NetDDE'} Where " _
        & "AssocClass=Win32_DependentService " & "Role=Antecedent" )
For each objService in colServiceList
    objService.StopService()
Next
Wscript.Sleep 20000
Set colServiceList = objWMIService.ExecQuery _
        ("Select * from Win32_Service where Name='NetDDE'")
For each objService in colServiceList
    errReturn = objService.StopService()
Next

Starting a Service and Its Dependents

Starts the NetDDE service and all its dependent services.

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colServiceList = objWMIService.ExecQuery _
    ("Select * from Win32_Service where Name='NetDDE'")
For each objService in colServiceList
    errReturn = objService.StartService()
Next
Wscript.Sleep 20000
Set colServiceList = objWMIService.ExecQuery("Associators of " _
   & "{Win32_Service.Name='NetDDE'} Where " _
        & "AssocClass=Win32_DependentService " & "Role=Dependent" )
For each objService in colServiceList
    objService.StartService()
Next

Starting AutoStart Services that have Stopped

Restarts any auto-start services that have been stopped.

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colListOfServices = objWMIService.ExecQuery _
 ("Select * from Win32_Service Where State = 'Stopped' and StartMode = " _
     & "'Auto'")
For Each objService in colListOfServices
    objService.StartService()
Next

Retrieving Service Status Changes from Event Logs

Retrieves events from the System event log that have an event ID of 7036. These events are recorded any time a service changes status.

Set dtmConvertedDate = CreateObject("WbemScripting.SWbemDateTime")
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colServiceEvents = objWMIService.ExecQuery _
    ("Select * from Win32_NTLogEvent Where Logfile = 'System' and " _
        & "EventCode = '7036'")
For Each strEvent in colServiceEvents
    dtmConvertedDate.Value = strEvent.TimeWritten
    Wscript.Echo dtmConvertedDate.GetVarDate   
    Wscript.Echo strEvent.Message
Next

Retrieving Service Status

Returns a list of all the services installed on a computer, and indicates their current status (typically, running or not running).

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colRunningServices = objWMIService.ExecQuery _
    ("Select * from Win32_Service")
For Each objService in colRunningServices
    Wscript.Echo objService.DisplayName  & VbTab & objService.State
Next

Retrieving Service Properties

Retrieves a complete list of services and their associated properties. Information is saved to a text file:

C:\Scripts\Service_List.cs.
Const ForAppending = 8
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objLogFile = objFSO.OpenTextFile("c:\scripts\service_list.csv", _
    ForAppending, True)
objLogFile.Write _
    ("System Name,Service Name,Service Type,Service State, Exit " _
        & "Code,Process ID,Can Be Paused,Can Be Stopped,Caption," _
        & "Description,Can Interact with Desktop,Display Name,Error " _
        & "Control, Executable Path Name,Service Started," _
        & "Start Mode,Account Name ")
objLogFile.Writeline
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colListOfServices = objWMIService.ExecQuery _
        ("Select * from Win32_Service")
For Each objService in colListOfServices
    objLogFile.Write(objService.SystemName) & ","
    objLogFile.Write(objService.Name) & ","
    objLogFile.Write(objService.ServiceType) & ","
    objLogFile.Write(objService.State) & ","
    objLogFile.Write(objService.ExitCode) & ","
    objLogFile.Write(objService.ProcessID) & ","
    objLogFile.Write(objService.AcceptPause) & ","
    objLogFile.Write(objService.AcceptStop) & ","
    objLogFile.Write(objService.Caption) & ","
    objLogFile.Write(objService.Description) & ","
    objLogFile.Write(objService.DesktopInteract) & ","
    objLogFile.Write(objService.DisplayName) & ","
    objLogFile.Write(objService.ErrorControl) & ","
    objLogFile.Write(objService.PathName) & ","
    objLogFile.Write(objService.Started) & ","
    objLogFile.Write(objService.StartMode) & ","
    objLogFile.Write(objService.StartName) & ","
    objLogFile.writeline
Next
objLogFile.Close

Resuming AutoStart Services that are Paused

Restarts any auto-start services that have been paused.

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colListOfServices = objWMIService.ExecQuery _
 ("Select * from Win32_Service Where State = 'Paused' and StartMode = 'Auto'")
For Each objService in colListOfServices
    objService.ResumeService()
Next

Removing a Service

Removes a hypothetical service named DbService.

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colListOfServices = objWMIService.ExecQuery _
    ("Select * from Win32_Service Where Name = 'DbService'")
For Each objService in colListOfServices
    objService.StopService()
    objService.Delete()
Next

Pausing Services Running Under a Specific Account

Pauses all services running under the hypothetical service account Netsvc.

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colServices = objWMIService.ExecQuery _
    ("Select * from Win32_Service")
For each objService in colServices
    If objService.StartName = ".\netsvc" Then
        errReturnCode = objService.PauseService()
    End If
Next

Monitoring Service Performance

Uses formatted performance counters to retrieve performance data for the DHCP Server service.

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
set objRefresher = CreateObject("WbemScripting.SWbemRefresher")
Set colDHCPServer = objRefresher.AddEnum _
    (objWMIService, "win32_PerfFormattedData_DHCPServer_DHCPServer"). _
          ObjectSet
objRefresher.Refresh
For i = 1 to 60
    For Each objDHCPServer in colDHCPServer
        Wscript.Echo "Acknowledgements per second: " & _
            objDHCPServer.AcksPerSec
        Wscript.Echo "Declines per second: " & _
            objDHCPServer.DeclinesPerSec
        Wscript.Echo "Discovers per second: " & _
            objDHCPServer.DiscoversPerSec
        Wscript.Echo "Informs per second: " & objDHCPServer.InformsPerSec
        Wscript.Echo "Offers per second: " & objDHCPServer.OffersPerSec
        Wscript.Echo "Releases per second: " & _
            objDHCPServer.ReleasesPerSec
        Wscript.Echo "Requests per second: " & _
            objDHCPServer.RequestsPerSec
    Next
    Wscript.Sleep 10000
    objRefresher.Refresh
Next

Installing a Service

Installs a hypothetical service Db.exe.

Const OWN_PROCESS = 16
Const NOT_INTERACTIVE = False
Const NORMAL_ERROR_CONTROL = 2
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set objService = objWMIService.Get("Win32_BaseService")
errReturn = objService.Create("DbService" ,"Personnel Database" , _
    "c:\windows\system32\db.exe", OWN_PROCESS, NORMAL_ERROR_CONTROL, "Manual", _
        NOT_INTERACTIVE, "NT AUTHORITY\LocalService", ""  )
Wscript.Echo errReturn

Enumerating Service Load Order Groups

Returns a list of all the service load order groups found on a computer, and well as their load order.

On Error Resume Next
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colItems = objWMIService.ExecQuery("Select * from Win32_LoadOrderGroup")
For Each objItem in colItems
    Wscript.Echo "Driver Enabled: " & objItem.DriverEnabled
    Wscript.Echo "Group Order: " & objItem.GroupOrder
    Wscript.Echo "Name: " & objItem.Name
    Wscript.Echo
Next

Enumerating Inactive Services

Returns a list of all the services installed on a computer that are currently stopped.

strComputer = "."

Set objWMIService = GetObject("winmgmts:" & _
    "{impersonationLevel=Impersonate}!\\" & strComputer & "\root\cimv2")
Set colStoppedServices = objWMIService.ExecQuery _
  ("SELECT DisplayName,State FROM Win32_Service WHERE State <> 'Running'")

For Each objService in colStoppedServices
    Wscript.Echo objService.DisplayName  & " = " & objService.State
Next

Enumerating Dependent Services for a Single Service

Enumerates all the services that cannot start until the Rasman service has started.

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colServiceList = objWMIService.ExecQuery("Associators of " _
   & "{Win32_Service.Name='rasman'} Where " _
        & "AssocClass=Win32_DependentService " & "Role=Antecedent" )
For Each objService in colServiceList
    Wscript.Echo objService.DisplayName
Next

Enumerating Dependent Services for All Services

Returns a list of all the services installed on a computer that are currently stopped.

Const ForAppending = 8
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objLogFile = _
     objFSO.OpenTextFile("c:\scripts\service_dependencies.csv", _
         ForAppending, True)
objLogFile.Write("Service Dependencies")
objLogFile.Writeline
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colListOfServices = objWMIService.ExecQuery _
    ("Select * from Win32_Service")

For Each objService in colListofServices
    objServiceRegistryName = objService.Name
    objServiceDisplayName = objService.DisplayName

Set colServiceList = objWMIService.ExecQuery("Associators of " _
   & "{Win32_Service.Name='" & objServiceRegistryName & "'} Where " & _
        "AssocClass=Win32_DependentService Role=Antecedent" )


 If colServiceList.Count = 0 then
        objLogFile.Write(objServiceDisplayName) & ", None"
        objLogFile.Writeline
    Else
        For Each objDependentService in colServiceList        
            objLogFile.Write(objServiceDisplayName) & ","
            objLogFile.Write(objDependentService.DisplayName) 
        Next
        objLogFile.WriteLine
    End If
Next
objLogFile.Close

Enumerating Antecedent Services for a Single Service

Enumerates all the services that must be running before the SMTP service can be started.

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colServiceList = objWMIService.ExecQuery("Associators of " _
 & "{Win32_service.Name='SMTPSVC'} Where " _
    & "AssocClass=Win32_DependentService " & "Role=Dependent")       
For Each objService in colServiceList
    Wscript.Echo objService.DisplayName
Next

Determining Services that can be Stopped

Returns a list of services that can be stopped.

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colServices = objWMIService.ExecQuery _
    ("Select * from Win32_Service Where AcceptStop = True")
For Each objService in colServices
    Wscript.Echo objService.DisplayName
Next

Determining Services Running in a Process

Returns a list of services running in the Services.exe process.

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colListOfServices = objWMIService.ExecQuery _
    ("Select * from Win32_Service")
For Each objService in colListOfServices
    If objService.PathName = "C:\WINDOWS\system32\services.exe" Then
        Wscript.Echo objService.DisplayName
    End If
Next

Determining Services Running in All Processes

Returns a list of processes and all the services currently running in each process.

set objIdDictionary = CreateObject("Scripting.Dictionary")
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colServices = objWMIService.ExecQuery _
    ("Select * from Win32_Service Where State <> 'Stopped'")
For Each objService in colServices
    If objIdDictionary.Exists(objService.ProcessID) Then
    Else
        objIdDictionary.Add objService.ProcessID, objService.ProcessID
    End If
Next
colProcessIDs = objIdDictionary.Items
For i = 0 to objIdDictionary.Count - 1
    Set colServices = objWMIService.ExecQuery _
        ("Select * from Win32_Service Where ProcessID = '" & _
            colProcessIDs(i) & "'")
    Wscript.Echo "Process ID: " & colProcessIDs(i)
    For Each objService in colServices
        Wscript.Echo VbTab & objService.DisplayName
    Next
Next

Determining Services that can be Paused

Returns a list of services that can be stopped.

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colServices = objWMIService.ExecQuery _
    ("Select * from Win32_Service Where AcceptPause = True")
For Each objService in colServices
    Wscript.Echo objService.DisplayName
Next

Configuring Service Start Options

Disables all services configured as manual start. Among other things, this prevents Power Users from being able to start these services.
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colServiceList = objWMIService.ExecQuery _
    ("Select * from Win32_Service where StartMode = 'Manual'")
For Each objService in colServiceList
    errReturnCode = objService.Change( , , , , "Disabled")  
Next

Configuring Service Error Control Codes

Configures all auto-start services to issue an alert if the service fails during startup.

Const NORMAL_ERROR_CONTROL = 2
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colServiceList = objWMIService.ExecQuery _
    ("Select * from Win32_Service where ErrorControl = 'Ignore'")
For Each objService in colServiceList
    errReturn = objService.Change( , , , NORMAL_ERROR_CONTROL)  
Next

Changing a Service Account Password

Changes the service account password for any services running under the hypothetical service account Netsvc.
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colServiceList = objWMIService.ExecQuery _
    ("Select * from Win32_Service")
For Each objservice in colServiceList
    If objService.Startname = ".\netsvc" Then
        errReturn = objService.Change( , , , , , , , "password") 
    End If
Next

WSH - Stop, Start service

strState = ""
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colRunningServices = objWMIService.ExecQuery _
    ("Select * from Win32_Service where Name='Themes' ")
For Each objService in colRunningServices
    Wscript.Echo objService.DisplayName  & VbTab & objService.State
  If objService.DisplayName = "Themes" Then
  If objService.State = " Running" Then
          errReturnCode = objService.StopService()
  Else
   errReturnCode = objService.StartService()
   End If
 End

SQL Server System Databases

An Introduction to SQL Server System Databases:

SQL Server 2008/2005) contain 5 special databases:
1. master
2. model
3. tempdb
4. msdb
5. and mssql system resource.

These databases are used by SQL Server for its own maintenance and management.


Master Database:
----------------
The master database contains all of the system level information for SQL Server – all of the logins, linked servers, endpoints, and other system-wide configuration settings. The master database is also where SQL Server stores information about the other databases on this instance and the location of their files. If the master database is not present, SQL Server cannot start.

Always take regular backups of the master database.
Since the master database hold all of the information related to logins, endpoints, linked servers, and user databases, it’s important that you take a backup of the master database after configuring any of these server level changes. Otherwise, if your SQL Server suffers a catastrophic failure, those changes will be lost to the sands of time.

 “Do not create user objects in master. Otherwise, master must be backed up more frequently.”

Model Database:
---------------
The model database is used as a template whenever a new user database is created. You can change most database properties, create users, stored procedures, tables, views, etc – whatever you do will be applied to any new databases.
The nice thing is that you can create a guaranteed set of users, stored procedures, and options (including collation options) by making changes to the model database. Once those changes are in place, they are applied to every new database.
Outside of its role as a template, model doesn’t do anything else.

MSDB Database:
-----------------
msdb is used by the SQL Server Agent, database mail, Service Broker, and other services. If you aren’t actively working with things like jobs, alerts, log shipping, etc you can pretty safely ignore msdb… sort of.
One important item is that msdb holds backup history. Using the msdb tables (you can start by taking a look at msdb.dbo.backupset), it’s possible to determine when each database and filegroup was last backed up. This is very useful, especially when you’ve just started working at a new company or taken over the maintenance of new servers.
A word of warning: you need to make sure that you are pruning old backup history from msdb. Leaving old backup data can slow down the performance of backup and restore operations, the sp_delete_backuphistory system stored procedure is mentioned. This stored procedure will delete information older than the @oldest_date parameter. It is important that you are incredibly careful when using this store procedure and don’t attempt to delete all of the backup history data in your msdb at once. Attempting to clear out a large number of database backup history records in one fell swoop can have an adverse effect on performance. I suggest removing the data one to two days at a time.

Resource database:
-------------------
The resource database is a hidden system database. This is where system objects are stored. It isn’t possible to see the resource database by normal means. However you can see the data file by navigating to C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\Binn. The exact size and modification data of this file will be different from version to version, but the modified date should be the same date that you see when you run SELECT @@version.
It is best to think of the resource database as if it were another system DLL. The resource database is designed to make it easy for quick database upgrades. If new system objects are being put in place, it is only necessary to swap out the resource database MDF file.
Typically, the only way to view the contents of the resource database is using the OBJECT_DEFINITION system function.
SELECT OBJECT_DEFINITION(OBJECT_ID('sys.objects'))

-- on my test system this yields the following:
CREATE VIEW sys.objects AS
    SELECT name, OBJECT_ID, principal_id, schema_id, parent_object_id,
        type, type_desc, create_date, modify_date,
        is_ms_shipped, is_published, is_schema_published
    FROM sys.objects$


Tempdb Database:
----------------
We come, at last, to tempdb. Tempdb is the workhorse of the system databases. It is the workspace that SQL Server uses to store the intermediate results of query processing and sorting. You know how you see those spools in your execution plans? When you see one of those, SQL Server is probably spooling the data to a temporary table in the tempdb. Outside of storing temporary results, tempdb is also used during snapshot isolation and for user created temporary tables (this includes table variables).
One thing that is interesting to note about tempdb is that it is re-created every time the SQL Server service is started. Any objects that you have created in tempdb will be gone once the server restarts. If you want specific tables or stored procedures to always be available in tempdb, you will need to add them to the model database or else use a stored procedure to create them in tempdb when the SQL Server is started.
A properly sized and configured tempdb is vital for effective SQL Server performance. By default tempdb starts at 8MB in size and will continue to grow by ten percent until the drive is full. If the tempdb is sized too small, system resources will be used growing the tempdb file. This overhead can be avoided by increasing the default size of tempdb.

What is IPSec?

IPSEC
-----
Short for IP Security, a set of protocols developed by the IETF to support secure exchange of packets at the IP layer.
IPsec has been deployed widely to implement Virtual Private Networks (VPNs).

IPsec supports two encryption modes: Transport and Tunnel.

* Transport mode encrypts only the data portion (payload) of each packet, but leaves the header untouched.

* The more secure Tunnel mode encrypts both the header and the payload.

On the receiving side, an IPSec-compliant device decrypts each packet.
For IPsec to work, the sending and receiving devices must share a public key.
This is accomplished through a protocol known as Internet Security Association and Key Management Protocol/Oakley (ISAKMP/Oakley), which allows the receiver to obtain a public key
and authenticate the sender using digital certificates.

Additional Info refer below address:
http://www.webopedia.com/TERM/I/IPsec.html

Windows PowerShell Config

WINDOWS POWER SHELL

PS C:\scripts> cd c:\windows
PS C:\WINDOWS> 
Or, if you prefer:
PS C:\scripts> chdir c:\windows
PS C:\WINDOWS>
Set location:
PS C:\scripts> Set-Location C:\Windows
PS C:\WINDOWS>
PS C:\WINDOWS> Get-Process
//to get recursive list of all items inside the folders. (-r)
> Get-ChildItem C:\Scripts -recurse
get-alias
get-command ...
$a = Get-ChildItem C:\Scripts
$a
Save as .ps1

Note : If you had any problem while running any PowerShell script, this could be one of the problem...then type below command at command prompt, and hit enter key...
> set-executionpolicy RemoteSigned

How to install:
--------------
1. Download and install the VMware VI Toolkit for Windows.
2. Download the VMware.VIToolkit.powerpack file that is attached to this article.
3. Open the PowerGUI Admin Console.
4. In the PowerGUI Admin Console, right-click the root node and select the Import menu command.
5. Import the VMware.VIToolkit.powerpack file that you downloaded in step 2.
6. Expand the "VMware" folder.
7. Select the "Managed VMware Hosts" node and use the "Add connection..." action to start adding the VMware hosts you want to manage with the VMware PowerPack.
8. Once you have added VMware hosts that you will manage, use any of the subnodes of the Managed VMware Hosts node to manage VMware objects or the host itself.

How to upgrade:
----------------
1. Download the VMware.VIToolkit.powerpack file that is attached to this article.
2. If you added or modified items in the PowerPack since installing it, close PowerGUI and then navigate to the Quest Software\PowerGUI subfolder of your roaming profile folder. You can find this folder by executing this string in PowerShell: "$([System.Environment]::GetFolderPath('ApplicationData'))\Quest Software\PowerGUI". In this folder, make a backup copy of your Quest.PowerGUI.xml file to ensure your customizations are backed up.
3. Open the PowerGUI Admin Console.
4. In the PowerGUI Admin Console, right-click the VMware folder and select the Delete menu command.
4. Once you have deleted the old version of the VMware PowerPack, right-click the root node and select the Import menu command.
5. Import the updated VMware.VIToolkit.powerpack file that you downloaded in step 1.
6. Once you have imported the updated VMware.VIToolkit.powerpack file, your VMware PowerPack will be up to date.
How to enable vDiagram support:
1. Download the VESI_Visio.zip file that is attached to this article.
2. If you agree to abide by the enclosed Legal Agreement document, extract the VESI_Visio.vss file into your 'My Shapes' folder. This can be found by entering the following string in PowerShell: "$([System.Environment]::GetFolderPath('MyDocuments'))\My Shapes".

BackTrack Commands

Some useful commands for Back Track Operating System

>ntfsmount /dev/hda1 /mnt/hda1 //mounting your physical hard disk
>mount
>cd /mnt/hda1/WINDOWS/system32/config //accessing your windows config folder
>cp SAM SAM_old
>cp SYSTEM SYSTEM_old
>cp SECURITY SECURITY_old
>chntpw SAM SYSTEM SECURITY
when it asks for password enter "*" -- it means blank password
>Reboot

login into windows without password - yes you can enter now !

Other commands:
cd /mnt/live/dev

Friday, October 15, 2010

Importing data from Excel Sheet into Oracle Database

The SQL file (generate_load.sql) generates the LOADDATA command. Place the generated LOADDATA command and the input file in the control file with the extension .ctl. The input file should be a comma separated file. Hence change the excel file into comma separated file.  SQL*Loader (sqlldr) is the utility to use for high performance data loads.  The data can be loaded from any text file and inserted into the database.


Steps to Import data from Excel into Oracle Database :

  1. Save the xls file as a comma separated file with extension .csv

2.   Execute the generate_load.sql file which will give you the LOADDATA command.
Save it into a control file with extension .ctl like example.ctl
SQL>@generate_load.sql
It will ask for the owner name and table name give the username(which is used to connect to sqlplus) and tablename in CAPS

3.   In the example.ctl file change the .txt file to the input .csv file

4.       sqlldr userid=scott/tiger control=example.ctl log=example.log bad = example.bad
On execution of this command it will insert the rows into the table. For any error just look into the log file and the .bad file.

NOTE: Remove the headings in the Excel file, if available.

userid  - The Oracle username and password
log                   - The name of the file used by SQL*Loader to log results
control - The name of the control file.  This file specifies the format of the data to be loaded.
bad     - A file that is created when at least one record from the input file is rejected.  The rejected data records are placed in this file.  A record could be rejected for many reasons, including a non-unique key or a required column being null.



--------------------------------------------- Load.sql ----------------------------

set trimspool on 
set serverout on 
clear buffer 
undef dumpfile 
undef dumptable 
undef dumpowner 
var maxcol number 
var linelen number 
var dumpfile char(40) 
col column_id noprint 
set pages 0 feed off termout on echo off verify off 
accept dumpowner char prompt 'Owner of table to dump: ' 
accept dumptable char prompt 'Table to dump: ' 

begin 
  select max (column_id) 
  into   :maxcol 
  from   all_tab_columns 
  where table_name = rtrim (upper ('&dumptable')) and 
         owner      = rtrim (upper ('&dumpowner')); 
         
  select sum (data_length) + (:maxcol * 3)
  into   :linelen 
  from   all_tab_columns 
  where table_name = rtrim (upper ('&dumptable')) and 
         owner      = rtrim (upper ('&dumpowner')); 
end; 
-- Build a basic control file 
set line 79 
spool dtmp.sql 
select 'spool '||lower ('&dumptable')||'.par' from dual; 
spool off 


select 'userid = /'||chr (10)|| 
       'control = '||lower ('&dumptable')||'.ctl'||chr (10)|| 
       'log = '||lower ('&dumptable')||'.log'||chr (10)|| 
       'bad = '||lower ('&dumptable')||'.bad'||chr (10) 
from   dual;
spool off

spool dtmp.sql 
select 'spool '||lower ('&dumptable')||'.ctl' from dual;
spool off 

select 'load data'||chr(10)|| 
       'infile '||''''||lower ('&dumptable')||'.txt'||''''||chr (10)|| 
       'into table &&dumptable'||chr (10)|| 
       'fields terminated by '||''''||','||''''||
       ' optionally enclosed by '||''''||'"'||''''||chr (10)||'('
from   dual;
select '   '||column_name||',', column_id 
from   all_tab_columns 
where table_name = upper ('&dumptable') and 
       owner      = upper ('&dumpowner') and 
       column_id < :maxcol 
union 
select '   '||column_name, column_id 
from   all_tab_columns 
where table_name = upper ('&dumptable') and 
       owner      = upper ('&dumpowner') and 
       column_id = :maxcol 
order by 2;
select ')' from dual;
spool off

Thursday, October 14, 2010

require,call,cut,pattern

*************** library.pl ************************
our $cmd='net user anand password /add';
************* mainprogram.pl **********************
# Windows command line execution
use warnings;
use Sum; # user defined package
$\="\n";
require "library.pl"; # this statement will compile and make ready for use
#print "Test Windows Command\n";
#our $cmd = ;
#chomp($cmd);
# $cmd = "net user perluser passw0rd!";
# print "$cmd";
# ` $cmd `;
sub commandParam {
# print "command is $cmd";
$out=system($cmd);
eval{'$x=10/0'}; # exception is stored in $? by default
print "exception is : $? \n";
#print $out;
#$out=$out>>8;
if($out==0)
{
print "success";
}
else
{
print "fail";
}
return 1;
}
&commandParam;
# return 1;
# Pattern matching
# $x=172.172.172.172
# $x=~ /(\d{1,3})\.\1\.\1\.\1/;
# $x=172.22.59.10
# $x =~ /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/;
# $x = 1.5.1.5
# $x =~ /(\d{1})\.(\d{1})\.\1\.\2/;
# To comment multiple lines
=cut
=cut

Win32 MsgBox

use Win32;
$\ = "\n";
MsgBox("Test", "This is a test", 48);
# display a message box with an exclamation mark and an 'Ok' button
 sub MsgBox {
    my ($caption, $message, $icon_buttons) = @_;
    my @return = qw/- Ok Cancel Abort Retry Ignore Yes No/;
    my $result = Win32::MsgBox($message, $icon_buttons, $caption);
    return $return[$result];
}
# Win32::CopyFile(FROM, TO, OVERWRITE)
print Win32::CopyFile("C:\\test.txt", "C:\\test1.txt", true);
print Win32::DomainName();
print Win32::FsType();
#print Win32::GetFullPathName();
print Win32::GetNextAvailDrive();

Telnet

use Net::Telnet;
our $TelnetLoginPrompt ='/C:\\\\Documents and Settings\\\\Administrator>$/i';      #'/C:\\\\Users\\\\Administrator>$/i';     # '/C:\\\\Documents and Settings\\\\Administrator>$/i';
print $TelnetLoginPrompt;
$AttackSourceIP = "127.0.0.1";
$telnet = Net::Telnet->new(timeout=>10, errmode=>'die', prompt => $TelnetLoginPrompt); # '/C:\\\\Documents and Settings\\\\Administrator>$/i'
$telnet->open($AttackSourceIP);   # $AttackSourceIP is global variable
$telnet->login('administrator','qa08@');

Writing to Log File

#!/usr/bin/perl
#   $Id: example-01.pl,v 1.1 2007-08-19 11:19:47 adam Exp $
#   Standard module loading
use strict;
use warnings;
use Log::Trivial;
#   Create a logging object
my $logger = Log::Trivial->new(
    log_file  => 'C:/example.log',
    log_tag   => $$,
    set_level => 3,
);
#   Do stuff #  Log it
$logger->write( 'Stuff worked' );
#   Do more stuff
#   Log that too
$logger->write( 'Did more stuff' );

=cut
# Creates Log file
use Log::Trivial;
$logfile = "C:\\IBM\\Perl Automation_1\\LogFiles\\fimlog\\SetUpStatus.xls";
print $logfile;
# $logger = Log::Trivial->new(log_file => "$logfile", log_level => 3, log_tag => q{});
$logger = Log::Trivial->new(log_file => $logfile, log_level => 1, log_tag => {});
$logger->write("PSW Setup Log\n");
$logger->write("PSW Automation Smoke Test Results Log");
$logger->write(" ");
$logger->write(" ");
=cut

File Handle

# Program to read directory
use warnings;
# file contains first line as 'helo' and second line as 'world'
$\ = "\n"; # newline character added after each print statement
# $* = 1;    # for multi line reading
open(LOG, '<C:/test.txt') || die "can't open";
print "opened";
while(<LOG>)
{
  #chop($_);  # removes last character in the line or word
  print $_;
  if ($_ =~ "helo")
  {
    print "Yes its helo";
  }
  else
  {
    print "else part - world";
  }
}
# working with directories
opendir(DIR, "C:/parent") || die "can't open directory";
@arr = readdir(DIR);
print join("::",@arr);
$len = @arr;
print $len;
rewinddir(DIR); # rewind is used to move to first position
while($file=readdir(DIR))
{
$pos = telldir(DIR);  # to get the position
print $file;
print $pos;
  if ($pos==30)
  {
    #  if you uncomment this line, it will run as infinite loop
    #  Seekdir is used to goto specified position
    # seekdir(DIR,5);
    print "go back to pos 30";
  }
}
mkdir("C:/parent/child4",0777);
rmdir("C:/parent/child4");
print "error ::".$!;    # . is used to concatenate two text messages.
# creates file if its not created, using > or >>(append), < readonly won't create file.
open(FHDLE, '>>C:/parent/abc.txt') || die "can't open";
# below print statement will write welcome in the file.
print FHDLE "welcome";
print FHDLE "Ananya";
# if we delete text in abc1, abc text also will get delete
# In Unix we can create file like below:
# system(touch "../abc.txt");
link("C:/parent/abc.txt","C:/parent/link.txt");
unlink("C:/parent/link.txt");
#print unlink("C:/parent/abc1.txt");

do, require, subroutine calls, pointers, references, dereferences

****************** docalled.pl *********************
use warnings;
$\ = "\n";
print "welcome : we are in doCalled.pl script";
$a = 10;
$b = 20;
$c = defined;
# $d = undef;

sub calc($a, $b)
{
$c = $a + $b;
print "C ::".$c;
}
&calc;

sub egsub
{
local($x, $y) = @_;
$result = $x+$y;
print "Result ::".$result;
# return($x++ * $y++);
}
&egsub(12,12);

# using arrays passed by reference (typeglobbing)
@a = ("1","2","3");
@b = ("4","5","6");
&egval(@a, @b);
sub egval
{
local(*a, *b) = @_;
# print @a; # prints 123
@a = ("a","b","c");
@b = ("d","e","f");
}
# print @a; print @b;
&egval; # array values will now change to a,b,c and d,e,f instead of 1,2,3 and 4,5,6
#print @a; print @b;

# array passed by reference
@a1 = ("apple","dog","cat");
@a2 = ("one","two","three");
&egsub7(\@a1, \@a2);
sub egsub7
{
local($a1ref, $a2ref) = @_;
#print $a1ref; # prints ARRAY(0x277c344)
#print $a2ref; # prints ARRAY(0x277c3a4)
#print @$a1ref; # prints appledogcat
#print @$a2ref; # prints onetwothree
@arr1 = @$a1ref;
print $arr1[0]; # prints apple
print "testing ".$$a1ref[1];
#foreach $e(@$a2ref)
$count = @$a2ref; # count stores length of the array
print $count;
for( $i=0; $i<=$count; $i++ ) { print $i; print $$a2ref[$i]; } @$a1ref = ("new","values","dude"); print @$a1ref; # prints newvaluesdude } # array of references @fruits = ("apple", "orange", "grape"); @vegies = ("onion", "carrot"); @collection = (\@fruits, \@vegies); $arry = $collection[0]; print "::".@$arry; # below - for loop statement prints both fruits and vegies items $len1 = @collection; #print $len1; # prints 2 for($i=0; $i<$len1; $i++) { $len1 = @{$collection[$i]}; # important step - to read array references # print $len1; # prints values as 3 and 2 as array size for($j=0; $j<$len1; $j++) { #print $collection[$i][$j]; or below statement , both same print $collection[$i]->[$j];
}
}

return 1;


*********************** docalling.pl **********************

# doCalling - call doCall script
# do - will load into memory, even if its already loaded, compile and executes.
# require - will not load if its already loaded, it take parameter as file path or filename.
# if both statements were used as below, its executing only once.
use warnings;
$\ = "\n";
do "E:\\practice perl programs\\doCalled.pl"; # do "doCalled.pl";
# require "E:\\practice perl programs\\doCalled.pl"; # require "doCalled.pl";
print "Yes doCalled.pl has executed !!!";
print "We are in doCalling.pl";
&calc;
&egsub(13,13);

Win32 package

use Win32;
$\ = "\n";
$OSVersion = Win32::GetOSVersion();
$NextAvailDrive = Win32::GetNextAvailDrive();
print "OS version shows in numeric :: ". "$OSVersion";
print "Next available drive is :: $NextAvailDrive";
print Win32::LoginName();
#print Win32::MsgBox("Hello",3);
print Win32::GetFullPathName("noname.pl");

shift, unshift, pop, push, splice

# shift, unshift, pop, push, splice
#use strict;
use warnings;
$\ = "\n";
print "Shift Operator - removes first element from the list/array";
my @testarray = ("alpha", "beta", "gamma");
# print $testarray[0];
# print @testarray;
my $val = shift(@testarray);
print $val;
print @testarray; # returns beta and gamma only
print "\n Unshift Operator - returns total elements.";
my @a = (a,b,c);
my $ret = unshift(@a,1,2,3);
print $ret; # returns numreic value 6.
print "\n POP Operator - removes top most element in the list ie., last element";
my @b = (11,12,13,14);
print pop(@b); # returns item which it is going to remove
print @b;
print "\n Push Operator - appends new element and returns new count NUMERIC.";
my @c = (1);
my $num = push(@c,2,4,6,8);
print $num;
print @c;
print "\n Splice Operator - returns list";
my @list = ("a","b","c","d","e");
my @result = splice(@list,0,3,"+","*","-");
print @result;
print @list;
return 1;

require, subroutine call, cut, pattern matching

*************** library.pl ************************
our $cmd='net user anand password /add';

************* mainprogram.pl **********************
# Windows command line execution
use warnings;
use Sum; # user defined package

$\="\n";
require "library.pl"; # this statement will compile and make ready for use
#print "Test Windows Command\n";
#our $cmd = ;
#chomp($cmd);
# $cmd = "net user perluser passw0rd!";
# print "$cmd";
# ` $cmd `;
sub commandParam {
# print "command is $cmd";

$out=system($cmd);
eval{'$x=10/0'}; # exception is stored in $? by default
print "exception is : $? \n";
#print $out;
#$out=$out>>8;
if($out==0)
{
print "success";
}
else
{
print "fail";
}
return 1;
}

&commandParam;
# return 1;

# Pattern matching
# $x=172.172.172.172

# $x=~ /(\d{1,3})\.\1\.\1\.\1/;

# $x=172.22.59.10

# $x =~ /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/;

# $x = 1.5.1.5
# $x =~ /(\d{1})\.(\d{1})\.\1\.\2/;

# To comment multiple lines
=cut
=cut

keys, values, delete, each, exists

#Keys, Values, delete, each, exists
use warnings;
$\="\n";
print "Keys & Values example";
my %kvpair = ("a",1,"b",2,"c",3);
print keys(%kvpair);
print values(%kvpair);
print "\n DELETE example returns value";
%Hash = (1,one,2,two,3,three);
print delete($Hash{1});
print %Hash;
print "\n EACH returns key and value";
%NumberWord = (1,one,2,two,3,three);
print("each()");
while (($number,$wordform)=each(%NumberWord))
{
print("$number:$wordform");
}
print "\n EXISTS returns true or false";
%test = (one,1,two, 2);
if (exists $test{one})
{
print "success";
}
else
{
print "failed";
}

shift, unshift, pop, push, splice

# shift, unshift, pop, push, splice
#use strict;
use warnings;
$\ = "\n";
print "Shift Operator - removes first element from the list/array";
my @testarray = ("alpha", "beta", "gamma");
# print $testarray[0];
# print @testarray;
my $val = shift(@testarray);
print $val;
print @testarray; # returns beta and gamma only
print "\n Unshift Operator - returns total elements.";
my @a = (a,b,c);
my $ret = unshift(@a,1,2,3);
print $ret; # returns numreic value 6.
print "\n POP Operator - removes top most element in the list ie., last element";
my @b = (11,12,13,14);
print pop(@b); # returns item which it has removed
print @b;
print "\n Push Operator - appends new element and returns new count NUMERIC.";
my @c = (1);
my $num = push(@c,2,4,6,8);
print $num;
print @c;
print "\n Splice Operator - returns list";
my @list = ("a","b","c","d","e");
my @result = splice(@list,0,3,"+","*","-");
print @result;
print @list;
return 1;

Wednesday, October 13, 2010

Types Of Testing

There are 18 types of testing.
1. Build Verification Testing.
2. Regression Testing.
3. Re – Testing.
4. α - Testing.
5. β - Testing.
6. Static Testing.
7. Dynamic Testing.
8. Installation Testing.
9. Compatibility Testing.
10. Monkey Testing
11. Exploratory Testing.
12. Usability Testing.
13. End – To – End Testing.
14. Port – Testing.
15. Reliability Testing
16. Mutation Testing.
17. Security Testing.
18. Adhoc Testing.


1) Sanitary Testing / Build Verification Testing / Build Accepting Testing.
It is a type of testing in which one will conduct overall testing on the released build in order to check weather it is proper for further details testing or not.

Some companies even call it as Sanitary Testing and also Smoke Testing. But some company’s will say that just before the release of the built the developer’s will conduct the overall testing in order to check weather the build is proper for detailed testing or not that is known as Smoke Testing and once the build is released once again the testers will conduct the over all testing in order to check weather the build is proper for further detailed testing or not. That is known as Sanitary Testing.

2) Regression Testing
It is a type of testing in which one will perform testing on the already tested functionality again and again this is usually done in scenarios (Situations).

Scenario 1:
When ever the defects are raised by the Test Engineer rectified by the developer and the next build is released to the testing department then the Test Engineer will test the defect functionality and it’s related functionalities once again.

Scenario 2:
When ever some new changes are requested by the customer, those new features are incorporated by the developers, next built is released to the testing department then the test engineers will test the related functionalities of the new features once again which are already tested. That is also known as regression testing.
Note:
Testing the new features for the first time is new testing but not the regression testing.

3) Re – Testing:
It is a type of testing in which one will perform testing on the same function again and again with multiple sets of data in order to come to a conclusion whether the functionality is working fine or not.

4) α - Testing:
It is a type of testing in which one (I.e., out Test Engineer) will perform user acceptance testing in our company in the presents of the customer.
Advantages:
If at all any defects are found there is a chance of rectifying them immediately.

5) β - Testing:
It is a type of testing in which either third party testers or end users will perform user acceptance testing in the client place before actual implementation.

6) Static Testing:
It is a type of testing in which one will perform testing on an application or it’s related factors with out performing any actions.
Ex: GUI Testing, Document Testing, Code reviewing and etc…

7) Dynamic Testing:
It is a type of testing in which one will perform testing on the application by performing same action.
Ex: Functional Testing.

8) Installation Testing:
It is a type of testing in which one will install the application in to the environment by following the guidelines given in the deployment document and if the installation is successful the one will come to a conclusion that the guidelines are correct otherwise the guidelines are not correct.

9) Compatibility Testing:
It is a type of testing in which one may have to install the application into multiple number of environments prepared with different combinations of environmental components in order to check whether the application is suitable with these environments or not. This is use usually done to the products.

10) Monkey Testing:
It is a type of testing in which one will perform some abnormal actions intentionally (wanted) on the application in order to check its stability.

11) Exploratory Testing:
It is a type of testing in which usually the domain expert will perform testing on the application parallel by exploring the functionality with out having the knowledge of requirements.

12) Usability Testing:
It is a type of testing in which one will concentrate on the user friendliness of the application.

13) End – To – End Testing:
It is a type of testing in which one will perform testing on a complete transaction from one end to another end.

14) Port Testing:
It is a type of testing in which one will check weather the application is comfortable or not after deploying it into the original clients environment.

15) Reliability Testing (or) Soak Testing:
It is a type of testing in which one will perform testing on the application continuously for long period of time in order to check its stability.

16) Mutation Testing:
It is a type of testing in which one will perform testing by doing some changes

For example usually the developers will be doing any many changes to the program and check it’s performance it is known as mutation testing.

17) Security Testing:
It is a type of testing in which one will usually concentrate on the following areas.
i) Authentication.
ii) Direct URL Testing.
iii) Firewall Leakage Testing.


i) Authentication Testing:
It is a type of testing in which a Test Engineer will enter different combinations of user names and passwords in order to check whether only the authorized persons are accessing the application or not.

ii) Direct URL Testing:
It is a type of testing in which a test engineer will specified the direct URL’s of secured pages and check whether they are been accessing or not.

iii) Firewall leakage Testing:
It is a type of testing in which one will enter as one level of user and try to access the other level unauthorized pages in order to check whether the firewall is working properly or not.

18) Adhoc Testing:
It is a type of testing in which one will perform testing on the application in his own style after understanding the requirements clearly.

Levels Of Testing

There are 5 levels of testing.
1) Unite level testing
2) Module level testing
3) Integration level testing
4) System level testing
5) User acceptance level testing


1) Unit level testing
If one performs testing on a unit then that level of testing is known as unit level testing. It is white box testing usually developers perform it.
Unit: - It is defined as a smallest part of an application.
2) Module level testing
If one perform testing on a module that is known as module level testing. It is black box testing usually test engineers perform it.

3) Integration level testing
Once the modules are developing the developers will develop some interfaces and integrate the module with the help of those interfaces while integration they will check whether the interfaces are working fine or not. It is a white box testing and usually developers or white box testers perform it.

The developers will be integrating the modules in any one of the following approaches.
i) Top Down Approach (TDA)
In this approach the parent modules are developed first and then integrated with child modules.
ii) Bottom Up Approach (BUA)
In this approach the child modules are developed first and the integrated that to the corresponding parent modules.
iii) Hybrid Approach
This approach is a mixed approach of both Top down and Bottom up approaches.
iv) Big Bang Approach
Once all the modules are ready at a time integrating them finally is known as big bang approach.

STUB :
While integrating the modules in top down approach if at all any mandatory module is missing then that module is replaced with a temporary program known as STUB.

DRIVER :
While integrating the modules in bottom up approach if at all any mandatory module is missing then that module is replaced with a temporary program known as DRIVER.

4) System level testing
Once the application is deployed into the environment then if one performs testing on the system it is known as system level testing it is a black box testing and usually done by the test engineers.

At this level of testing so many types of testing are done.

Some of those are :
1. System Integration Testing
2. Load Testing
3. Performance Testing
4. Stress Testing etc….
5) User acceptance testing.
The same system testing done in the presents of the user is known as user acceptance testing. It s a black box testing usually done by the Test engineers.

Testing Methodology

TESTING METHODOLOGY (OR) TESTING TECHNIQUES

There are 3 methods are there
1. Black Box Testing.
2. White Box Testing.
3. Gray Box Testing

1 Black Box Testing
It is a method of testing in which one will perform testing only on the functional part of an application with out having any structural knowledge. Usually test engineers perform it.

2 White box Testing (Or) Glass box Testing (Or) Clear box Testing
It is a method of testing in which one will perform testing on the structural part of an application. Usually developers are white box testers perform it.

3 Gray box Testing
It is a method of testing in which one will perform testing on both the functional part as well as the structural part of an application.

Note:
The Test engineer with structural Knowledge will perform gray box testing.

Tuesday, October 12, 2010

SDLC Concepts

SDLC (Software Development Life Cycle) :

It contains 6 phases.
* INITIAL PHASE / REQUIREMENT PHASE.
* ANALYSIS PHASE.
* DESIGN PHASE.
* CODING PHASE.
* TESTING PHASE.
* DELIVERY AND MAINTENANCE PHASE.

Initial Phase :
Task:
Interacting with the customer and gathering the requirements.
Roles:
BA (Business Annalist)
EM (Engagement Manager)
Process:
First of all the business analyst will take an appointment from the customer, collects the templates from the company meets the customer on the appointed date gathers the requirements with the support of the templates and comeback to the company with a requirements documents. Then the engagement manager will check for the extra requirements if at all he fined any extra requirements he is responsible for the excess cast of the project. The engagement manager is also responsible for prototype demonstration in case of confused requirements.

Template:
It is defined as a pre-defined format with pre-defined fields used for preparing a document perfectly.

Prototype:
It is a rough and rapidly developed model used for demonstrating to the client in order to gather clear requirements and to win the confidence of a customer.

Proof:
The proof of this phase is requirements document which is also called with the following name
FRS - (Functional Requirement Specification)
BRS - (Business Requirement Specification)
CRS - (Client/Customer Requirement Specification)
URS - (User Requirement Specification)
BDD - (Business Design Document)
BD - (Business Document)

Note: Some company’s may the over all information in one document called as ‘BRS’ and the detailed information in other document called ‘FRS’. But most of the company’s will maintain both of information in a single document.

Analysis Phase :
Task:
Feasibility study.
Tentative planning.
Technology selection.
Requirement Analysis.

Roles:
System Analyst (SA)
Project Manager (PM)
Team Manager (TM)
Process:
(I) Feasibility study It is detailed study of the requirements in order to check whether all the requirements are possible are not.
(II) Tentative planning the resource planning and time planning is temporary done in this section.
(III) Technology selection the lists of all the technologies that are to be used to accomplish the project successfully will be analyzed listed out hear in this section.
(IV) Requirement analysis
The list of all the requirements like human resources, hardware, software required to accomplish this project successfully will be clearly analyzed and listed out hear in this section.

Proof:
The proof of this phase is SRC (Software Requirement Specification).

Design phase :
Tasks:
HLD (High Level Designing)
LLD (Low Level Designing)

Roles:
HLD is done by the CA (Chief Architect).
LLD is done by the TL (Technical Lead).

Process :
The chief architect will divided the whole project into modules by drawing some diagrams and technical lead will divided each module into sub modules by drawing some diagrams using UML (Unified Modeling Language).
The technical lead will also prepare the PSEUDO Code.

Proof:
The proof of this phase is technical design document (TDD).

Pseudo Code:
It is a set of English instructions used for guiding the developer to develop the actual code easily.

Module:
Module is defined as a group of related functionalities to perform a major task.

Coding Phase :
Task:
Programming / Coding.
Roles:
Developers / Programmers.
Process:
Developers will develop the actual source code by using the PSUEDO Code and following the coding standards like proper indentation, color-coding, proper commenting and etc.

Proof :
The proof of this phase is SCD (Source Code Document).

Testing Phase :
Task:
Testing.
Roles:
Test Engineer.
Process:
1. First of all the Test Engineer will receive the requirement documents and review it for under studying the requirements.

2. If at all they get any doubts while understanding the requirements they will prepare the Review Report (RR) with all the list of doubts.

3. Once the clarifications are given and after understanding the requirements clearly they will take the test case template and write the test cases.

4. Once the build is released they will execute the test cases.

5. After executions if at all find any defects then they will list out them in a defect profile document.

6. Then they will send defect profile to the developers and wait for the next build.

7. Once the next build is released they will once again execute the test cases

8. If they find any defects they will follow the above procedure again and again till the product is defect free.

9. Once they feel product is defect free they will stop the process.

Proof:
The proof of this phase is Quality Product.
Test case:
Test case is an idea of a Test Engineer based on the requirement to test a particular feature.

Delivery and Maintenance phase :
Delivery:
Task:
Installing application in the client environment.
Roles:
Senior Test Engineers / Deployment Engineer.
Process:
The senior test engineers are deployment engineer will go to the client place and install the application into the client environment with the help of guidelines provided in the deployment document.

Maintenance:
After the delivery if at all any problem occur then that will become a task based on the problem the corresponding roll will be appointed. Based on the problem role will define the process and solve the problem.


Additional Info:
Where exactly testing comes in to picture?
Which many sort of testing are there?

There are two sorts of testing.
1. Unconventional testing
2. Conventional testing

Unconventional Testing:
It is a sort of testing in which quality assurance people will check each and every out come document right from the initial phase of the SDLC.

Conventional Testing:
It is a sort of testing in which the test engineer will test the application in the testing phase of SDLC.
 

©2010 Software Testing powered by Free Blogger Templates | Author : Anand Satish