VBS: Connecting to a VM without User/Passwrd

Option Explicit
Const ForReading = 1

Dim WshShell,objReadTextFile,remoteDesktopName,addCredential

set WshShell=CreateObject(“WScript.Shell”)

remoteDesktopName = InputBox(“1 : ISM” & chr(10) & “2 : AUD” & chr(10) & “3 : SBM/SPI” & chr(10) & “4 : LSM” & chr(10) & “5 : STVM” & chr(10) & “6 : GRCF” & chr(10) & “7 : MET” & chr(10) & “8 : RSK” & chr(10) & “9 : SURVEYS” & chr(10) & “10 : EMN/BIA/BCM” & chr(10) & “11 : CIM” & chr(10) & “12 : CMS” & chr(10) & “13 : CMP” & chr(10) & “14 : TRG” & chr(10) & “15 : GRCI” & chr(10) & “16 : CITAP” & chr(10) & “17 : DMS” & chr(10) & “18 : RI VM” , “REMOTE DESKTOP CONNECTION”)

Select Case remoteDesktopName
Case 1
call RemoteDesktop(“msi-vmdevautmnism”)
Case 2
call RemoteDesktop(“msi-vmdevrsmautmn”)
Case 3
call RemoteDesktop(“msi-vmpqaautmnsp”)
Case 4
call RemoteDesktop(“vmipqarndautomet”)
Case 5
call RemoteDesktop(“vmipqaitgrcautmet”)
Case 6
call RemoteDesktop(“msi-vmdevautgrcf”)
Case 7
call RemoteDesktop(“Vmidevrndautomet”)
Case 8
call RemoteDesktop(“msi-vmdevautrsk”)
Case 9
call RemoteDesktop(“msi-vmdevautmnsurys”)
Case 10
call RemoteDesktop(“vmipqabcmautomet”)
Case 11
call RemoteDesktop(“vmipqacimautm”)
Case 12
call RemoteDesktop(“msi-vmdevautmncms”)
Case 13
call RemoteDesktop(“vmipqacmpautm”)
Case 14
call RemoteDesktop(“vmipqatrgautm”)
Case 15
call RemoteDesktop(“vmipqagrciautm”)
Case 16
call RemoteDesktop(“msi-vmdevcitap”)
Case 17
call RemoteDesktop(“msi-vmdevautmndms”)
Case 18
call RemoteDesktop(“vmipqariautoap”)

End Select

Function RemoteDesktop(remoteDesktopName)
addCredential = “cmdkey /generic:” & chr(34) & remoteDesktopName & chr(34) & ” /user:SYSTEMI\automation.team” & ” /pass:welcome*123″
WshShell.run addCredential
WshShell.run “mstsc /v: ” & chr(34) & remoteDesktopName & chr(34) & ” ” & “/f”
End Function

BAT file: Clearing cookies, cache of the browsers and all the temporary file

erase “%TEMP%\*.*” /f /s /q
for /D %%i in (“%TEMP%\*”) do RD /S /Q “%%i”

erase “%TMP%\*.*” /f /s /q
for /D %%i in (“%TMP%\*”) do RD /S /Q “%%i”

erase “%ALLUSERSPROFILE%\TEMP\*.*” /f /s /q
for /D %%i in (“%ALLUSERSPROFILE%\TEMP\*”) do RD /S /Q “%%i”

erase “%SystemRoot%\TEMP\*.*” /f /s /q
for /D %%i in (“%SystemRoot%\TEMP\*”) do RD /S /Q “%%i”

@rem Clear IE cache – (Deletes Temporary Internet Files Only)
RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 8
@rem (Deletes ALL History)
RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 255
@rem (Deletes History Only)
RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 1
@rem (Deletes Cookies Only)
RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 2
@rem (Deletes Form Data Only)
RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 16 (Deletes Form Data Only)
@rem (Deletes Password History Only)
RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 32 (Deletes Password History Only)
@rem (Deletes All)
rundll32.exe InetCpl.cpl,ClearMyTracksByProcess 4351
set DataDir=C:\Users\%USERNAME%\AppData\Local\Microsoft\Intern~1
del /q /s /f “%DataDir%”
rd /s /q “%DataDir%”
set History=C:\Users\%USERNAME%\AppData\Local\Microsoft\Windows\History
del /q /s /f “%History%”
rd /s /q “%History%”
set IETemp=C:\Users\%USERNAME%\AppData\Local\Microsoft\Windows\Tempor~1
del /q /s /f “%IETemp%”
rd /s /q “%IETemp%”
set Cookies=C:\Users\%USERNAME%\AppData\Roaming\Microsoft\Windows\Cookies
del /q /s /f “%Cookies%”
rd /s /q “%Cookies%”
erase “%LOCALAPPDATA%\Microsoft\Windows\Tempor~1\*.*” /f /s /q
for /D %%i in (“%LOCALAPPDATA%\Microsoft\Windows\Tempor~1\*”) do RD /S /Q “%%i”

@rem Clear Google Chrome cache
erase “%LOCALAPPDATA%\Google\Chrome\User Data\*.*” /f /s /q
for /D %%i in (“%LOCALAPPDATA%\Google\Chrome\User Data\*”) do RD /S /Q “%%i”

@rem Clear Firefox cache
erase “%LOCALAPPDATA%\Mozilla\Firefox\Profiles\*.*” /f /s /q
for /D %%i in (“%LOCALAPPDATA%\Mozilla\Firefox\Profiles\*”) do RD /S /Q “%%i”

Python,SVN: Update the SVN folder

mfastUrlforCorewrapper=”http://rndsvn/svn/MFAST/MFASTTestHarness/” + ciVariables.MFASTVersion +”/TestScripts/corewrappers.sah”
svnExportCmd=”svn export –username=”+ciVariables.svnUser+” –password=”+ciVariables.svnPwd+” –force ” +mfastUrlforCorewrapper+” “+scriptFolder

def updateMFAST():
”’
This function updates the MFAST folder with corewrapper and mfastutils and lib folder
@returns None
”’
scriptFolder = os.path.join(ciVariables.mfastHome,”TestScripts”)
mfastutilsFolder = os.path.join(ciVariables.mfastHome,”Testdata”,”mfastutils”)
if(ciVariables.updateMFAST==”YES”):
#deleting Corewrapper file
corewrappersFile=scriptFolder+”/corewrappers.sah”
if os.path.isfile(corewrappersFile):
os.remove(corewrappersFile,dir_fd=None)
#Copying the new Corewrapper file
#svn export command
mfastUrlforCorewrapper=”http://rndsvn/svn/MFAST/MFASTTestHarness/” + ciVariables.MFASTVersion +”/TestScripts/corewrappers.sah”
svnExportCmd=”svn export –username=”+ciVariables.svnUser+” –password=”+ciVariables.svnPwd+” –force ” +mfastUrlforCorewrapper+” “+scriptFolder
svnExportStatus=subprocess.call(svnExportCmd,stderr=subprocess.STDOUT,shell=True)
if svnExportStatus == 0:
print(“INFO: “,mfastUrlforCorewrapper,” successfully downloaded to “,scriptFolder)
returnStatus= True

else:
print(“ERORR: “,mfastUrlforCorewrapper,” could not be downloaded to “,scriptFolder)
returnStatus= False
#deleting mfastutilsFolder
#if os.path.exists(mfastutilsFolder):
# shutil.rmtree(mfastutilsFolder)
# print(“INFO: Removed the “,mfastutilsFolder ,”directory from Testdata”)
# os.makedirs(mfastutilsFolder)
# print(“INFO: Recreated the”,mfastutilsFolder ,”directory from Testdata”)
#else:
# print(“INFO: “,mfastutilsFolder,” directory doesn’t exist in MFAST Testdata folder.Creating it”)
# os.makedirs(mfastutilsFolder)
#mfastutils=”http://rndsvn/svn/MFAST/MFASTTestHarness/” + ciVariables.MFASTVersion +”/Testdata/mfastutils/”
#svnExportCmdutils=”svn export –username=”+ciVariables.svnUser+” –password=”+ciVariables.svnPwd+” –force ” +mfastutils+” “+mfastutilsFolder
#svnExportStatusutils=subprocess.call(svnExportCmdutils,stderr=subprocess.STDOUT,shell=True)
#if svnExportStatusutils == 0:
# print(“INFO: “,mfastutils,” successfully downloaded to “,mfastutilsFolder)
# returnStatus= True

#else:
# print(“ERORR: “,mfastutils,” could not be downloaded to “,mfastutilsFolder)
# returnStatus= False
else:
print(“MFAST folder update skipped”)

Python: Send Email

def sendEmail(emailSubject,body):
”’
This function is will send email updates to the recipient

@toRecipient: mail id to which mail will be sent
@emailSubject: subject of the mail
@body: body of the mail
”’
sender = ‘dev1@dev.com’
#list receivers = [toRecipient]
#receivers = [toRecipient]
receivers= ciVariables.emailRecipient.split(“,”)

#message = “””From: From CI -Admin
#To: To Dev Team
#Subject: emailSubject

#body
#”””

msg = MIMEMultipart()
msg[‘From’]=”From Daily CI Admin -” + sender
listOfRecievers = len(receivers)
print(listOfRecievers)
recieversName=””
for i in range(listOfRecievers):
recieversName = recieversName +receivers[i]+”;”
print(recieversName)
msg[‘To’]= recieversName
msg[‘Subject’]=emailSubject
msgbody = body
msg.attach(MIMEText(msgbody, ‘plain’))
text = msg.as_string()

#login to SMTP server details
username = ‘dev1@dev’
password = ‘welcome123’

try:
smtpObj= smtplib.SMTP(‘msi-vmdevrcap’,25)
smtpObj.login(username,password)
smtpObj.sendmail(sender, receivers, text)
smtpObj.quit()
print (“Successfully sent email”)
except Exception:
print (“Error: unable to send email”)

rem # Sub process to send Email
:SendEMail
call:GetDateTime
@echo %DD%-%MM%-%YY% %hr%:%min%:%sec% “INFO: Sending status mail started to %Recipient%”>>%LOGFILE%
echo %Recipient%
echo %EMAIL_SUB%
echo %EMAIL_MESSAGE%
python -c ^
“import ciFunctions ; ^
ciFunctions.sendEmail(“%EMAIL_SUB%”,”%EMAIL_MESSAGE%”)”
call:GetDateTime
@echo %DD%-%MM%-%YY% %hr%:%min%:%sec% “INFO: Mail sent successfully to %Recipient%”>>%LOGFILE%

Calling Python through batch file and getting date and time

call:SendEmail %Recipient% %EMAIL_SUB% %EMAIL_MESSAGE%

:SendEMail
call:GetDateTime
@echo %DD%-%MM%-%YY% %hr%:%min%:%sec% “INFO: Sending status mail started to %Recipient%”>>%LOGFILE%
echo %Recipient%
echo %EMAIL_SUB%
echo %EMAIL_MESSAGE%
python -c ^
“import ciFunctions ; ^
ciFunctions.sendEmail(“%EMAIL_SUB%”,”%EMAIL_MESSAGE%”)”
call:GetDateTime
@echo %DD%-%MM%-%YY% %hr%:%min%:%sec% “INFO: Mail sent successfully to %Recipient%”>>%LOGFILE%

rem # Sub process to get date and time for logging
:GetDateTime
for /f “delims=” %%a in (‘wmic OS Get localdatetime ^| find “.”‘) do set dt=%%a
set datestamp=%dt:~0,8%
set timestamp=%dt:~8,6%
set DD=%datestamp:~6,2%
set MM=%datestamp:~4,2%
set YY=%datestamp:~0,4%
set hr=%timestamp:~0,2%
set min=%timestamp:~2,2%
set sec=%timestamp:~4,2%

goto:EOF

Open, save and close Ms Excel through vbs

strPath = “D:\M7Regression\AutomationTool\MFAST\7.0\TestData”

Set objExcel = CreateObject(“Excel.Application”)
objExcel.Visible = True
objExcel.DisplayAlerts = False

Set objFso = CreateObject(“Scripting.FileSystemObject”)
Set objFolder = objFso.GetFolder (strPath)

For Each objFile In objFolder.Files

If objFso.GetExtensionName (objFile.Path) = “xls” OR objFso.GetExtensionName (objFile.Path) = “xlsx” Then
Set objWorkbook = objExcel.Workbooks.Open(objFile.Path)
‘objWorkbook.Open
objWorkbook.Save
objWorkbook.Close True ‘Save changes
End If

Next

objExcel.Quit

PYTHON: Reading HTML file available in a folder and printing data into Notepad(works for sahi reports)

# Will read the Sahi results and print the Total,Passed,Failed steps into notepad

import configparser
import sys
import os
import shutil
import subprocess
import smtplib
import errno
import time
#import configobj
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import datetime
from datetime import date
from bs4 import BeautifulSoup

def updateResultStat():
”’
This function is will update the result status in table CI_EXECUTION_STATUS
@ciRunNo – Execution id of the CI run
@candidateName – Installer Name of the CI run
@endTime – End time of the CI run
@ciStatus – CI STatus
@moduleName – Module Name
@version – Module Version
”’
resultHome=”D:\\M7Regression\\LatestAutomationResults\\”
CreateFile()
for folderName in os.listdir(resultHome):
folderPath = resultHome +”\\”+ folderName
#os.system(“pause”)
totalStep=0
totalPassSteps=0
totalFailSteps=0
startTime=0
endTime=0
browser,startTime,endTime,totalStep,totalPassSteps,totalFailSteps = getTestStepcount(folderPath+”\\”)
WriteResultsToFile(folderName,browser,startTime,endTime,totalStep,totalPassSteps,totalFailSteps)
print(“INFO: Results Updated Please check ConsolidatedResult.txt file”)
os.system(“pause”)

def getTestStepcount(baseFolder):
”’
This function is will get the no of test steps passed and failed for complete execution
@baseFolder – Report folder path where CI TC’s execution status count needs to be updated
returns totalSteps,totalPassSteps,totalFailSteps
”’
B_Browser=0
S_StartTime=0
E_EndTime=0
Total_test_run=0
Total_Testcases_passed=0
Total_Testcases_failed=0

#for file in os.listdir(baseFolder):
# passSteps=0
# failSteps=0
# if file.endswith(“.html”):
# if file == “index.html”:
# fileName=baseFolder+”\\”+file
# B_Browser,S_StartTime,E_EndTime = getTestStepsCount(fileName)

for file in os.listdir(baseFolder):
if file.endswith(“.html”):
if file == “testcase_summary.html”:
fileName=baseFolder+”\\”+file
Total_test_run,Total_Testcases_passed,Total_Testcases_failed = getTestStepsCountIndexHTML(fileName)
return B_Browser,S_StartTime,E_EndTime,Total_test_run,Total_Testcases_passed,Total_Testcases_failed

def getTestStepsCount(fileName):
”’
This function is will get the no of pass steps and fail steps for one script
@fileName – fileName which needs to be searched for success tag
returns passSteps,failedCount
”’
Browser=0
StartTime=0
EndTime=0

try:
#fileText=open(fileName,’r’)
fileText=open(fileName, encoding=”utf8″)
soup = BeautifulSoup(fileText)
testcase_summary_table=soup.find(‘table’,{‘class’:’suite_summary_part’})
testcase_summary_table_td=testcase_summary_table.find_all(‘td’)
tdCount=0
for td in testcase_summary_table_td:
if tdCount==1:
Browser=td.text
if tdCount==3:
StartTime=td.text
if tdCount==5:
EndTime=td.text
tdCount=tdCount+1
fileText.close()
except IOError as fileOpenError:
print(“INFO”)
finally:
return Browser,StartTime,EndTime

def getCommentedCount(fileName):
”’
This function is will get the no of commented test steps for one script
@fileName – fileName which needs to be searched for success tag
returns commentedCount
”’
commentedCount=0
fileText=open(fileName,’r’)
soup = BeautifulSoup(fileText)
for tr in soup.find_all(‘tr’,{‘class’:[‘SUCCESS’]}) :
for td in tr.find_all(‘td’):
if td.text.find(‘//’)== 0:
commentedCount=commentedCount+1
break
if td.text.find(‘Test Case Id’)== 0:
commentedCount=commentedCount+1
break
fileText.close()
return(commentedCount)

def getTestStepsCountIndexHTML(fileName):
”’
This function is will get the no of pass steps and fail steps for one script
@fileName – fileName which needs to be searched for success tag
returns passSteps,failedCount
”’
commentedSteps=0
Total_testcases_run=0
Testcases_passed=0
Testcases_failed=0

try:
#fileText=open(fileName,’r’)
fileText=open(fileName, encoding=”utf8″)
print(fileName)
#print(fileText)
#time.sleep(3)
#os.system(“pause”)
soup = BeautifulSoup(fileText)
suite_summary_table=soup.find(‘table’,{‘class’:’suite_summary’})
suite_summary_td=suite_summary_table.find_all(‘td’)
tdCount=0
for td in suite_summary_td:
if tdCount==11:
Total_testcases_run=td.text
if tdCount==13:
Testcases_passed=td.text
if tdCount==15:
Testcases_failed =td.text
tdCount=tdCount+1
fileText.close()
except IOError as fileOpenError:
print(“ERROR: Error in opening file”)
os.system(“pause”)
finally:
return Total_testcases_run,Testcases_passed,Testcases_failed

def CreateFile():
”’
This function is will get the no of pass steps and fail steps for one script
@fileName – fileName which needs to be searched for success tag
returns passSteps,failedCount
”’
try:
f = open(“ConsolidatedResult.txt”,”w”) #opens file with name of “test.txt”
f.write(“FolderName\t\tTotalScripts\tTotalPassed\tTotalFailed”)
f.close()
except IOError as fileOpenError:
print(“ERROR: in creating ConsolidatedResult.txt”)
os.system(“pause”)
finally:
print(“INFO: ConsolidatedResult.txt File Created”)

def WriteResultsToFile(folderName,browser,startTime,endTime,totalStep,totalPassSteps,totalFailSteps):
”’
This function is will get the no of pass steps and fail steps for one script
@fileName – fileName which needs to be searched for success tag
returns passSteps,failedCount
”’
folderName,browser,startTime,endTime,totalStep,totalPassSteps,totalFailSteps
try:
f = open(“ConsolidatedResult.txt”,”a”)
f.write(“\n” + str(folderName) + “\t\t” + str(totalStep) + “\t” + str(totalPassSteps) + “\t” + str(totalFailSteps))
f.close()
except IOError as fileOpenError:
print(“ERROR: In updating the ConsolidatedResult.txt file”)
os.system(“pause”)
finally:
print(“Writing Total, Passed, Failed steps into ConsolidatedResult.txt for the folder ” + folderName)