Unable to download the windows update using script - vbscript

I am running Windows 2015 LTSB and use below script to download the Windows patches as and when required.
Previously the below script use to work from normal user, but from past few days it just shows the message as
Download completed successfully. Please press any key to continue.
Where actually nothing is downloaded and this script doesn't go to install updates.
And when I execute the same script from user with Admin privileges, it downloads and installs the relevant update packages.
I suspect that downloader.Download() is behaving differently for Admin and Normal user.
Can you please assist me in knowing what is the cause of updates not getting downloaded from normal user.
Option Explicit
Dim updateSession, updateSearcher, update, searchResult, downloader, updatesToDownload, updatesToInstall, installer, installationResult, InputKey, i, endKey
If Right((LCase(WScript.FullName)),11) <> "cscript.exe" Then
WScript.Echo "Please carry out this script using CSCRIPT.EXE." & _
vbCrLf & "Example: cscript WindowsUpdate.vbs"
WScript.StdOut.Write vbCrLf & "Please press any key to continue."
endKey = WScript.StdIn.ReadLine
WScript.Quit(0)
End If
Dim strInp
On Error Resume Next
WScript.Echo "Press Enter key to begin Windows Update."
strInp = WScript.StdIn.ReadLine
WScript.Echo "------------------------------"
WScript.Echo "Windows Update"
WScript.Echo "------------------------------"
WScript.Echo "Verifying latest update..."
Set updateSession = CreateObject("Microsoft.Update.Session")
Set updateSearcher = updateSession.CreateupdateSearcher()
Set searchResult = _
updateSearcher.Search("IsInstalled=0 and Type='Software' and AutoSelectOnWebSites=1")
'If Err.Number <> 0 Then
If IsNull(searchResult.Updates.Count) Or IsEmpty(searchResult.Updates.Count) Then
WScript.Echo "An error occurred. Please check your network connection and try again."
WScript.StdOut.Write vbCrLf & "Please press any key to continue."
endKey = WScript.StdIn.ReadLine
'Err.Clear
WScript.Quit(0)
End If
For i = 0 To searchResult.Updates.Count-1
Set update = searchResult.Updates.Item(i)
WScript.Echo i + 1 & vbTab & update.Title & " Size: " & update.MaxDownloadSize
Next
If searchResult.Updates.Count = 0 Then
WScript.Echo "Windows is up to date."
WScript.StdOut.Write vbCrLf & "Please press any key to continue."
endKey = WScript.StdIn.ReadLine
WScript.Quit(0)
Else
WScript.Echo "A newer version of " & searchResult.Updates.Count & _
" is found. Downloading starts."
End If
WScript.StdOut.Write "Preparing download..."
Set updatesToDownload = CreateObject("Microsoft.Update.UpdateColl")
For i = 0 to searchResult.Updates.Count-1
Set update = searchResult.Updates.Item(i)
WScript.StdOut.Write "."
updatesToDownload.Add(update)
Next
WScript.Echo vbCrLf & "Newer version of programs is downloading..."
Set downloader = updateSession.CreateUpdateDownloader()
downloader.Updates = updatesToDownload
downloader.Download()
'WScript.Echo "DEBUG [downloader.Download().ResultCode]:" & downloader.Download().ResultCode
If downloader.Download().ResultCode = 2 Then
WScript.Echo "Download completed successfully."
Else
WScript.Echo "Download failed."
End If
If downloader.Download().ResultCode = 4 Then
WScript.StdOut.Write vbCrLf & "Please press any key to continue."
endKey = WScript.StdIn.ReadLine
WScript.Quit(0)
End If
WScript.Echo "Download the following programs is successfully completed."
For i = 0 To searchResult.Updates.Count-1
Set update = searchResult.Updates.Item(i)
If update.IsDownloaded Then
WScript.Echo i + 1 & vbTab & update.Title
End If
Next
Set updatesToInstall = CreateObject("Microsoft.Update.UpdateColl")
WScript.StdOut.Write "Preparing installation..."
For i = 0 To searchResult.Updates.Count-1
Set update = searchResult.Updates.Item(i)
If update.IsDownloaded = True Then
WScript.StdOut.Write "."
updatesToInstall.Add(update)
End If
Next
'WScript.StdOut.Write vbCrLf & "DEBUG [updatesToInstall.Count]:" & updatesToInstall.Count
If updatesToInstall.Count = 0 Then
WScript.Echo vbCrLf & "Installation failed."
WScript.StdOut.Write vbCrLf & "Please press any key to continue."
endKey = WScript.StdIn.ReadLine
WScript.Quit(0)
End If
WScript.Echo vbCrLf & "Installing..."
Set installer = updateSession.CreateUpdateInstaller()
installer.Updates = updatesToInstall
Set installationResult = installer.Install()
If installationResult.ResultCode = 2 Then
WScript.Echo "Installation completed successfully."
Else
WScript.Echo "Installation failed."
End If
WScript.Echo "Detail information."
For i = 0 to updatesToInstall.Count - 1
WScript.StdOut.Write i + 1 & vbTab & _
updatesToInstall.Item(i).Title
If installationResult.GetUpdateResult(i).ResultCode = 2 then
WScript.Echo "Succeed."
Else
WScript.Echo "Failure."
End If
Next
'WScript.StdOut.Write "Restart is required."
If installationResult.RebootRequired Then
'WScript.Echo "Required."
WScript.Echo "Computer restart is required to complete installation."
Else
WScript.Echo "Computer restart is not required."
End If
WScript.StdOut.Write vbCrLf & "Please press any key to continue."
InputKey = WScript.StdIn.ReadLine
If installationResult.RebootRequired Then
Dim objWshShell
Set objWshShell = WScript.CreateObject("WScript.Shell")
objWshShell.Run "%comspec% /c shutdown /r /t 0", 0, False
WScript.Quit(-1)
Else
WScript.Quit(0)
End If

Related

Disabling/ignoring the Windows service "Windows Registry"

I have this VBscript, which is fairly simple, however, I'm asking if its possible to add a line of code, that disables the "Windows Registry" service, that usually runs on every windows machine.
'----------------------------------------------------------------
' Type: Monitor
' Desc: Check to see if ANY services are set to auto start but are not running
' Input:
' Output: Output (String) - Output message to return
' Alert: If ANY services meet the criteria
' Author: Simon McBryde
' Ver: 1.0
'----------------------------------------------------------------
'----------------------------------------------------------------
' Initialize input variables
'----------------------------------------------------------------
Set wshShell = CreateObject( "WScript.Shell" )
strAttemptStart = wshShell.ExpandEnvironmentStrings( "%AttemptStart%" )
'----------------------------------------------------------------
' Main script logic
'----------------------------------------------------------------
Dim objWMIService, objService, colService, strComputer, strOutput
strComputer = "."
Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colService = objWMIService.ExecQuery ("Select * from Win32_Service")
strOutput = ""
strRestart = ""
For Each objService in colService
If objService.StartMode = "Auto" And objService.State <> "Running" Then
strOutput = strOutput & objService.DisplayName & " (" & objService.Name & "), " & "Current state: " & objService.State
If strAttemptStart = "true" Then
strResult = objService.StartService()
Select Case strResult
Case 0 strOutput = strOutput & ", Restart result: " & "Success"
Case 1 strOutput = strOutput & ", Restart result: " & "Not Supported"
Case 2 strOutput = strOutput & ", Restart result: " & "Access Denied"
Case 3 strOutput = strOutput & ", Restart result: " & "Dependent Services Running"
Case 4 strOutput = strOutput & ", Restart result: " & "Invalid Service Control"
Case 5 strOutput = strOutput & ", Restart result: " & "Service Cannot Accept Control"
Case 6 strOutput = strOutput & ", Restart result: " & "Service Not Active"
Case 7 strOutput = strOutput & ", Restart result: " & "Service Request Timeout"
Case 8 strOutput = strOutput & ", Restart result: " & "Unknown Failure"
Case 9 strOutput = strOutput & ", Restart result: " & "Path Not Found"
Case 10 strOutput = strOutput & ", Restart result: " & "Service Already Running"
Case 11 strOutput = strOutput & ", Restart result: " & "Service Database Locked"
Case 12 strOutput = strOutput & ", Restart result: " & "Service Dependency Deleted"
Case 13 strOutput = strOutput & ", Restart result: " & "Service Dependency Failure"
Case 14 strOutput = strOutput & ", Restart result: " & "Service Disabled"
Case 15 strOutput = strOutput & ", Restart result: " & "Service Logon Failure"
Case 16 strOutput = strOutput & ", Restart result: " & "Service Marked For Deletion"
Case 17 strOutput = strOutput & ", Restart result: " & "Service No Thread"
Case 18 strOutput = strOutput & ", Restart result: " & "Status Circular Dependency"
Case 19 strOutput = strOutput & ", Restart result: " & "Status Duplicate Name"
Case 20 strOutput = strOutput & ", Restart result: " & "Status Invalid Name"
Case 21 strOutput = strOutput & ", Restart result: " & "Status Invalid Parameter"
Case 22 strOutput = strOutput & ", Restart result: " & "Status Invalid Service Account"
Case 23 strOutput = strOutput & ", Restart result: " & "Status Service Exists"
Case 24 strOutput = strOutput & ", Restart result: " & "Service Already Paused"
End Select
End If
strOutput = strOutput & " ***** "
End If
Next
If strOutput <> "" Then GenerateAlert strOutput, 1
'----------------------------------------------------------------
' Output result and quit with required exit code
'----------------------------------------------------------------
Sub GenerateAlert (strOutput, intExitCode)
WScript.Echo "<-Start Result->"
WScript.Echo "Output=" & strOutput
WScript.Echo "<-End Result->"
WScript.Quit intExitCode
End Sub
Restrict the results of your WQL query if you want to ignore the service:
"SELECT * FROM Win32_Service WHERE Name <> 'RemoteRegistry'"
Add a condition if you want to stop the service:
If strAttemptStart = "true" Then
If objService.Name = "RemoteRegistry" Then
strResult = objService.StopService()
Else
strResult = objService.StartService()
End If
Select Case strResult
...
End Select
End If

VBS Script for Windows Update

How would I remove the users request to "approve" everything in this .VBS script and instead just let it autorun/install everything found?
Details on how the script runs:
This .VBS script here runs on the Windows computer, searchs for Windows Update, then manually ask the user to "okay" each update it finds. Once the user hits "okay" and accepts the updates found, it then downloads it.
Once the Widnows Updates downloads, it then asks the user again to approve each Windows Update install. Which is not automated..... I'm not familiar with .VBS enough to edit this script.
Set updateSession = CreateObject("Microsoft.Update.Session")
updateSession.ClientApplicationID = "MSDN Sample Script"
Set updateSearcher = updateSession.CreateUpdateSearcher()
WScript.Echo "Searching for updates..." & vbCRLF
Set searchResult = _
updateSearcher.Search("IsInstalled=0 and Type='Software' and IsHidden=0")
WScript.Echo "List of applicable items on the machine:"
For I = 0 To searchResult.Updates.Count-1
Set update = searchResult.Updates.Item(I)
WScript.Echo I + 1 & "> " & update.Title
Next
If searchResult.Updates.Count = 0 Then
WScript.Echo "There are no applicable updates."
WScript.Quit
End If
WScript.Echo vbCRLF & "Creating collection of updates to download:"
Set updatesToDownload = CreateObject("Microsoft.Update.UpdateColl")
For I = 0 to searchResult.Updates.Count-1
Set update = searchResult.Updates.Item(I)
addThisUpdate = false
If update.InstallationBehavior.CanRequestUserInput = true Then
WScript.Echo I + 1 & "> skipping: " & update.Title & _
" because it requires user input"
Else
If update.EulaAccepted = false Then
WScript.Echo I + 1 & "> note: " & update.Title & _
" has a license agreement that must be accepted:"
WScript.Echo update.EulaText
WScript.Echo "Do you accept this license agreement? (Y/N)"
strInput = WScript.StdIn.Readline
WScript.Echo
If (strInput = "Y" or strInput = "y") Then
update.AcceptEula()
addThisUpdate = true
Else
WScript.Echo I + 1 & "> skipping: " & update.Title & _
" because the license agreement was declined"
End If
Else
addThisUpdate = true
End If
End If
If addThisUpdate = true Then
WScript.Echo I + 1 & "> adding: " & update.Title
updatesToDownload.Add(update)
End If
Next
If updatesToDownload.Count = 0 Then
WScript.Echo "All applicable updates were skipped."
WScript.Quit
End If
WScript.Echo vbCRLF & "Downloading updates..."
Set downloader = updateSession.CreateUpdateDownloader()
downloader.Updates = updatesToDownload
downloader.Download()
Set updatesToInstall = CreateObject("Microsoft.Update.UpdateColl")
rebootMayBeRequired = false
WScript.Echo vbCRLF & "Successfully downloaded updates:"
For I = 0 To searchResult.Updates.Count-1
set update = searchResult.Updates.Item(I)
If update.IsDownloaded = true Then
WScript.Echo I + 1 & "> " & update.Title
updatesToInstall.Add(update)
If update.InstallationBehavior.RebootBehavior > 0 Then
rebootMayBeRequired = true
End If
End If
Next
If updatesToInstall.Count = 0 Then
WScript.Echo "No updates were successfully downloaded."
WScript.Quit
End If
If rebootMayBeRequired = true Then
WScript.Echo vbCRLF & "These updates may require a reboot."
End If
WScript.Echo vbCRLF & "Would you like to install updates now? (Y/N)"
strInput = WScript.StdIn.Readline
WScript.Echo
If (strInput = "Y" or strInput = "y") Then
WScript.Echo "Installing updates..."
Set installer = updateSession.CreateUpdateInstaller()
installer.Updates = updatesToInstall
Set installationResult = installer.Install()
'Output results of install
WScript.Echo "Installation Result: " & _
installationResult.ResultCode
WScript.Echo "Reboot Required: " & _
installationResult.RebootRequired & vbCRLF
WScript.Echo "Listing of updates installed " & _
"and individual installation results:"
For I = 0 to updatesToInstall.Count - 1
WScript.Echo I + 1 & "> " & _
updatesToInstall.Item(i).Title & _
": " & installationResult.GetUpdateResult(i).ResultCode
Next
End If
Script output via WScript.Echo method: run your script using the command-line-based script host (e.g. Cscript.exe YourScript.vbs).
User input: replace strInput = WScript.StdIn.Readline with strInput = "Y" (all occurrences in your script).
To keep update log: use Cscript.exe YourScript.vbs > YourLog.txt.
Explanation:
Whether you use WScript or CScript, you still run the scripts in the same manner. The difference is only in the output — WScript generates windowed output, while CScript sends its output to the command window in which it was started. On initial installation, the default host is WScript. To change it to CScript, type the following at the command line: cscript //h:cscript.
I'd not use Cscript.exe YourScript.vbs < Prepared-Y.txt redirection: we don't know number of Y lines in input file as we can't estimate number of updates in advance; could lead to an error Microsoft VBScript runtime error: Input past end of file
Read Redirection

wscript FTP download error

I am trying to use this vbs script by naterice.com. It seems working but downloaded files, or file are blank. Any idea? (Windows 2000, IIS6). Thanks.
DIM sSite
DIM sUsername
DIM sPassword
DIM sLocalPath
DIM sRemotePath
DIM sRemoteFile
sSite="xxx.xxx.xx"
sUsername="yyyy"
sPassword="password"
sLocalPath="C:\rss"
sRemotePath="/directory"
sRemoteFile="*.htm"
FTPDownload sSite, sUsername, sPassword, sLocalPath, sRemotePath, sRemoteFile
Function FTPDownload(sSite, sUsername, sPassword, sLocalPath, sRemotePath, sRemoteFile)
'This script is provided under the Creative Commons license located
'at http://creativecommons.org/licenses/by-nc/2.5/ . It may not
'be used for commercial purposes with out the expressed written consent
'of NateRice.com
Const OpenAsDefault = -2
Const FailIfNotExist = 0
Const ForReading = 1
Const ForWriting = 2
Set oFTPScriptFSO = CreateObject("Scripting.FileSystemObject")
Set oFTPScriptShell = CreateObject("WScript.Shell")
sRemotePath = Trim(sRemotePath)
sLocalPath = Trim(sLocalPath)
sOriginalWorkingDirectory = oFTPScriptShell.CurrentDirectory
oFTPScriptShell.CurrentDirectory = sLocalPath
'--------END Path Checks---------
'build input file for ftp command
sFTPScript = sFTPScript & "USER " & sUsername & vbCRLF
sFTPScript = sFTPScript & sPassword & vbCRLF
sFTPScript = sFTPScript & "cd " & sRemotePath & vbCRLF
sFTPScript = sFTPScript & "binary" & vbCRLF
' sFTPScript = sFTPScript & "ascii" & vbCRLF
sFTPScript = sFTPScript & "prompt n" & vbCRLF
sFTPScript = sFTPScript & "mget " & sRemoteFile & vbCRLF
sFTPScript = sFTPScript & "quit" & vbCRLF & "quit" & vbCRLF & "quit" & vbCRLF
sFTPTemp = oFTPScriptShell.ExpandEnvironmentStrings("%TEMP%")
sFTPTempFile = sFTPTemp & "\" & oFTPScriptFSO.GetTempName
sFTPResults = sFTPTemp & "\" & oFTPScriptFSO.GetTempName
'Write the input file for the ftp command
'to a temporary file.
Set fFTPScript = oFTPScriptFSO.CreateTextFile(sFTPTempFile, True)
fFTPScript.WriteLine(sFTPScript)
fFTPScript.Close
Set fFTPScript = Nothing
oFTPScriptShell.Run "%comspec% /c FTP -n -s:" & sFTPTempFile & " " & sSite & " > " & sFTPResults, 0, TRUE
Wscript.Sleep 1000
'Check results of transfer.
Set fFTPResults = oFTPScriptFSO.OpenTextFile(sFTPResults, ForReading, FailIfNotExist, OpenAsDefault)
sResults = fFTPResults.ReadAll
fFTPResults.Close
'oFTPScriptFSO.DeleteFile(sFTPTempFile)
'oFTPScriptFSO.DeleteFile (sFTPResults)
If InStr(sResults, "226 Transfer complete.") > 0 Then
FTPDownload = True
ElseIf InStr(sResults, "File not found") > 0 Then
FTPDownload = "Error: File Not Found"
ElseIf InStr(sResults, "cannot log in.") > 0 Then
FTPDownload = "Error: Login Failed."
Else
FTPDownload = "Error: Unknown."
End If
Set oFTPScriptFSO = Nothing
Set oFTPScriptShell = Nothing
End Function
Hello, I am trying to use this vbs script by naterice.com. It seems working but downloaded files, or file are blank. Any idea? (Windows 2000, IIS6). Thanks.
Here's an example that downloads a text file from MS's ftp server and saves it in the c:\user folder.
Run it in a command prompt with cscript to see error messages (both server and local), or change Outp.write to message boxes.
cscript "c:\path to script\ftp.vbs"
You must specify the url absolutely correctly. There isn't a helper to work out what you mean. Match case on the server path eg README.TXT on the server should also be upper case in your URL.
ADODB is a binary format. The code you had would only work reliably on English computers as windows translates characters for the language used. This code originally downloaded MS's Safety Scanner.
Set fso = CreateObject("Scripting.FileSystemObject")
Set Outp = Wscript.Stdout
On Error Resume Next
Set File = WScript.CreateObject("Microsoft.XMLHTTP")
File.Open "GET", "ftp://ftp.microsoft.com/Softlib/README.TXT", False
File.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 1.1.4322; .NET CLR 3.5.30729; .NET CLR 3.0.30618; .NET4.0C; .NET4.0E; BCD2000; BCD2000)"
File.Send
If err.number <> 0 then
Outp.writeline ""
Outp.writeline "Error getting file"
Outp.writeline "=================="
Outp.writeline ""
Outp.writeline "Error " & err.number & "(0x" & hex(err.number) & ") " & err.description
Outp.writeline "Source " & err.source
Outp.writeline ""
Outp.writeline "HTTP Error " & File.Status & " " & File.StatusText
Outp.writeline File.getAllResponseHeaders
End If
On Error Goto 0
Set BS = CreateObject("ADODB.Stream")
BS.type = 1
BS.open
BS.Write File.ResponseBody
BS.SaveToFile "c:\users\ReadMe.txt", 2
Thanks Fred for assistance, at the end I have found out that I have got some networks problems with my server. It accepts some traffic but not all... This may explain why the first script by naterice.com has been working at my computer and was not working at the server. The same may be true with your script.

Automatic Windows Updates Via VBS without user interaction

I have the script from msdn
but dont solve nothing if i need to stay there waiting for input "Y" whenever is needed, what i actually want is simply bypass that point.
I already tried to modify it but cant get it working since i dont know much from vbs.
WUA_SearchDownloadInstall.vbs Content:
Set updateSession = CreateObject("Microsoft.Update.Session")
updateSession.ClientApplicationID = "MSDN Sample Script"
Set updateSearcher = updateSession.CreateUpdateSearcher()
WScript.Echo "Searching for updates..." & vbCRLF
Set searchResult = _
updateSearcher.Search("IsInstalled=0 and Type='Software' and IsHidden=0")
WScript.Echo "List of applicable items on the machine:"
For I = 0 To searchResult.Updates.Count-1
Set update = searchResult.Updates.Item(I)
WScript.Echo I + 1 & "> " & update.Title
Next
If searchResult.Updates.Count = 0 Then
WScript.Echo "There are no applicable updates."
WScript.Quit
End If
WScript.Echo vbCRLF & "Creating collection of updates to download:"
Set updatesToDownload = CreateObject("Microsoft.Update.UpdateColl")
For I = 0 to searchResult.Updates.Count-1
Set update = searchResult.Updates.Item(I)
addThisUpdate = false
If update.InstallationBehavior.CanRequestUserInput = true Then
WScript.Echo I + 1 & "> skipping: " & update.Title & _
" because it requires user input"
Else
If update.EulaAccepted = false Then
WScript.Echo I + 1 & "> note: " & update.Title & _
" has a license agreement that must be accepted:"
WScript.Echo update.EulaText
WScript.Echo "Do you accept this license agreement? (Y/N)"
strInput = WScript.StdIn.Readline
WScript.Echo
If (strInput = "Y" or strInput = "y") Then
update.AcceptEula()
addThisUpdate = true
Else
WScript.Echo I + 1 & "> skipping: " & update.Title & _
" because the license agreement was declined"
End If
Else
addThisUpdate = true
End If
End If
If addThisUpdate = true Then
WScript.Echo I + 1 & "> adding: " & update.Title
updatesToDownload.Add(update)
End If
Next
If updatesToDownload.Count = 0 Then
WScript.Echo "All applicable updates were skipped."
WScript.Quit
End If
WScript.Echo vbCRLF & "Downloading updates..."
Set downloader = updateSession.CreateUpdateDownloader()
downloader.Updates = updatesToDownload
downloader.Download()
Set updatesToInstall = CreateObject("Microsoft.Update.UpdateColl")
rebootMayBeRequired = false
WScript.Echo vbCRLF & "Successfully downloaded updates:"
For I = 0 To searchResult.Updates.Count-1
set update = searchResult.Updates.Item(I)
If update.IsDownloaded = true Then
WScript.Echo I + 1 & "> " & update.Title
updatesToInstall.Add(update)
If update.InstallationBehavior.RebootBehavior > 0 Then
rebootMayBeRequired = true
End If
End If
Next
If updatesToInstall.Count = 0 Then
WScript.Echo "No updates were successfully downloaded."
WScript.Quit
End If
If rebootMayBeRequired = true Then
WScript.Echo vbCRLF & "These updates may require a reboot."
End If
WScript.Echo vbCRLF & "Would you like to install updates now? (Y/N)"
strInput = WScript.StdIn.Readline
WScript.Echo
If (strInput = "Y" or strInput = "y") Then
WScript.Echo "Installing updates..."
Set installer = updateSession.CreateUpdateInstaller()
installer.Updates = updatesToInstall
Set installationResult = installer.Install()
'Output results of install
WScript.Echo "Installation Result: " & _
installationResult.ResultCode
WScript.Echo "Reboot Required: " & _
installationResult.RebootRequired & vbCRLF
WScript.Echo "Listing of updates installed " & _
"and individual installation results:"
For I = 0 to updatesToInstall.Count - 1
WScript.Echo I + 1 & "> " & _
updatesToInstall.Item(i).Title & _
": " & installationResult.GetUpdateResult(i).ResultCode
Next
End If
You could try to replace all instances of
strInput = WScript.StdIn.Readline
with
strInput = "Y"
As if the user has selected Yes each time.

Getting & Managing/updating local built-in accounts for some Windows domain & standalone servers (vbscript)

**
Hi!
I was wondering if someone tried something similar, I have some code merged with a lot of glue...but as i'm a newby in vbs I can be sure that most of it is wrong. Basically I wanted to save a lot time during built-in admin accounts review /update with an automatic vbscript for this task.
I have like 6 account names and each one with an specific passwords.
I'm not 100% sure of which local account name is being used into each server but that might be something that i will need to verify manually or try to see if I can use another file where this script will read the possible accounts names and passwords and use some kind of brute force
Here is what I have :**
**update 8-29-12 a (deleted)
**update 8-29-12 b "THIS ONE IS WORKING..but i need to test & use cpau for NDC's"
Option Explicit
Dim strExcelPath, objExcel, objSheet, intRow, strUserDN, strPassword, comp
Dim objUser
' Spreadsheet file.
strExcelPath = "c:\List.xls"
' Bind to Excel object.
On Error Resume Next
Set objExcel = CreateObject("Excel.Application")
If (Err.Number <> 0) Then
On Error GoTo 0
Wscript.Echo "Excel application not found."
Wscript.Quit
End If
On Error GoTo 0
' Open spreadsheet.
On Error Resume Next
objExcel.Workbooks.Open strExcelPath
If (Err.Number <> 0) Then
On Error GoTo 0
Wscript.Echo "Spreadsheet cannot be opened: " & strExcelPath
Wscript.Quit
End If
On Error GoTo 0
' Bind to worksheet.
Set objSheet = objExcel.ActiveWorkbook.Worksheets(1)
intRow = 2
Do While objSheet.Cells(intRow, 1).Value <> ""
comp = objSheet.Cells(intRow, 1).Value
strUserDN = objSheet.Cells(intRow, 2).Value
strPassword = objSheet.Cells(intRow, 3).Value
On Error Resume Next
Set objuser = GetObject ("WinNT://" & comp & "/" & strUserDN & ",user")
If (Err.Number <> 0) Then
On Error GoTo 0
Wscript.Echo "Data NOT found: "
Else
objUser.SetPassword strPassword
If (Err.Number <> 0) Then
On Error GoTo 0
Wscript.Echo "Password NOT set for: " & strUserDN
Else
End If
End If
intRow = intRow + 1
Loop
' Close the workbook.
objExcel.ActiveWorkbook.Close
' Quit Excel.
objExcel.Application.Quit
Wscript.Echo "Done"
My option "B" could be start over using something like this:
#echo off
for /F "delims=" %%i in (servers.txt) do (
psexec \%%i NET USER > %%i.txt
)
**
There might hundreds of ways to solve this and the my idea it's avoid having someone manually modifying the admin passwords for the servers listed and not listed in the AD after one month.
Any help would be appreciated.
Regards
This code will list the local users for one computer, specified by the variable server, and then print the user id of each user.
server = "YourServerName"
Set oComputer = GetObject("WinNT://" & server & "")
oComputer.Filter = Array("User")
For Each oUser in oComputer
WScript.Echo oUser.Name
Next
'Objective: check multiple servers for admin accounts status and report to html file
Set iFSO = CreateObject("Scripting.FilesyStemObject")
Set oFSO = CreateObject("Scripting.FilesyStemObject")
InputFile = WScript.Arguments.Named("servers")
if len(InputFile) < 1 then
wscript.echo "Error: Servers Parameter not found" & vbCrLf
show_usage
wscript.quit
end if
Outputfile= InputFile & "_guest_admins_" + cstr(Month(now()))+"_"+cstr(day(now()))+".htm"
if not ofso.FileExists(inputfile) then
wscript.echo "Error: Server list file not Found."
wscript.quit
end if
Set ofile = ofso.createTextFile(OutputFile, True)
Set ifile = iFSO.OpenTextFile(inputfile)
ofile.writeline "<html>" & html_head & "<body>"
ofile.writeline "<table border=1 cellpadding=1 cellspacing=0>"
ofile.writeline o
ofile.writeline "<tr><td>Hostname</td><td>User</td><td>Disabled</td><td>Locked</td><td>Expiration Date</td><td>Flags</td><td>BuiltIn</td></tr>"
Do until ifile.AtEndOfLine
Computer = ifile.ReadLine
if ping(Computer) then
Builtin = ""
if Check_WMI(Computer) then
Builtin = GetBuiltInAccount(Computer)
else
Builtin = "WMI Fail"
end if
strt = now
wscript.echo "Checking Users for server: " & Computer
on error resume next
Set objGroup = GetObject("WinNT://" & Computer & "/Administrators,group")
if err.number <> 0 then
wscript.echo "GetObject WinNT Failed"
ofile.writeline "<tr><td>" & computer & "</td><td colspan=6 align=center>GetObject WinNT Fail: "& err.number &"</td></tr>"
else
on error goto 0
For Each objUser in objGroup.Members
ofile.writeline GetUserNT(computer, objUser.Name, Builtin)
Next
wscript.echo "Elapsed Time: " & datediff("s", strt, now) & " seconds"
end if
else
wscript.echo computer & " does not reply ping"
ofile.writeline "<tr><td>" & computer & "</td><td colspan=6 align=center>No Ping Reply</td></tr>"
end if
Loop
ofile.writeline "</table>"
ofile.writeline "</body></html>"
function ping(target)
strComputer = "."
Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colPingedComputers = objWMIService.ExecQuery("Select * from Win32_PingStatus Where Address = '"& target & "'")
For each objComputer in colPingedComputers
' If the status code is Null or Not 0 then the ping failed
If IsNull( objComputer.StatusCode ) Or objComputer.StatusCode <> 0 Then
' Set the function to return Boolean FALSE
Ping = False
Else
' Set the function to return Boolean TRUE
Ping = True
End If
Next
end function
sub show_usage
wscript.echo "Usage: cscript chkusers /servers:list.txt" & vbcrlf
wscript.echo vbtab & "/servers Parameter is a Text File one Servername per Line" & vbcrlf
wscript.echo "Notes: This script generates an html report of server admin accounts."
wscript.echo " Results are saved in a file named + date + htm extension."
wscript.echo " Output example filename: list_guest_admins_" + cstr(Month(now()))+"_"+cstr(day(now()))+".htm"
end sub
Function Check_WMI(strServer)
On Error Resume Next ' error handling off
' create object reference, connect to namespace root\default
Set oCimOmId = GetObject("winmgmts:"& strServer & "\root\default:__cimomidentification=#")
' Test whether WMI is present or not.
If Err <> 0 then
Check_WMI= true
else
Check_WMI= false
end if
on error goto 0
end function
Sub EnumNameSpaces(strNameSpace)
'call enumnamespaces("root")
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\" & strNameSpace)
Set colNameSpaces = objWMIService.InstancesOf("__NAMESPACE")
For Each objNameSpace In colNameSpaces
Call EnumNameSpaces(strNameSpace & "\" & objNameSpace.Name)
Next
End Sub
function CSS
tt = "<style type=""text/css"">" & vbcrlf
tt=tt & " body {font-family:Verdana;font-size: 10px;color: #49403B;background: #EFEFEF;}" & vbcrlf
tt=tt & "table {font-family:Verdana;font-size: 12px; empty-cells:show; }" & vbcrlf
tt=tt & "</style>" & vbcrlf
CSS = tt
end function
function html_head
tt="<head>" & vbcrlf
tt=tt & CSS
html_head = tt & "</head>" & vbcrlf
end function
function GetUserNT(strComputer, usr, bltin)
Const ADS_UF_DONT_EXPIRE_PASSWD = &H10000
o=""
On Error Resume Next
Set objUser = GetObject("WinNT:// " & strComputer & "/" & usr & " ")
o=o& "<tr><td>"& strcomputer &"</td><td>"& usr &"</td>"
if len(objUser.AccountDisabled) = 0 then exit function
o=o& "<td> "& StrDisabled(objUser.AccountDisabled) &"</td>"
o=o& "<td> "& StrLocked(objUser.IsAccountLocked) &"</td>"
o=o& "<td> "
o=o& objUser.Get("UserFlags") AND ADS_UF_DONT_EXPIRE_PASSWD
o=o& "</td>"
o=o& "<td> "
o=o& objUser.AccountExpirationDate
o=o& "</td>"
if lcase(bltin) = lcase(usr) then
o=o & "<td> Built-In</td>"
elseif instr(bltin, "[[Fail]]") > 0 then
o=o & "<td> "& bltin &"</td>"
else
o=o & "<td> </td>"
end if
o = o & "</tr>"
GetUserNT = o
end function
function StrLocked(str)
if str = "True" then
StrLocked = "Locked"
else
StrLocked = "Unlocked"
end if
end function
function StrDisabled(str)
if str = "True" then
StrDisabled = "Disabled"
else
StrDisabled = "Enabled"
end if
end function
function GetUsers(strComputer,grp,usr)
On Error Resume Next
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colItems = objWMIService.ExecQuery("Select * from Win32_UserAccount Where name = '"& usr &"'")
o=""
For Each objItem in colItems
o=o& "<tr>"
o=o& "<td>" & strComputer & "</td>"
o=o& "<td>" & grp & "</td>"
o=o& "<td>" & objItem.AccountType & "</td>"
o=o& "<td>" & objItem.Caption & "</td>"
o=o& "<td>" & objItem.Description & "</td>"
o=o& "<td>" & objItem.Disabled & "</td>"
o=o& "<td>" & objItem.Domain & "</td>"
o=o& "<td>" & objItem.FullName & "</td>"
o=o& "<td>" & objItem.LocalAccount & "</td>"
o=o& "<td>" & objItem.Lockout & "</td>"
o=o& "<td>" & objItem.Name & "</td>"
o=o& "<td>" & objItem.PasswordChangeable & "</td>"
o=o& "<td>" & objItem.PasswordExpires & "</td>"
o=o& "<td>" & objItem.PasswordRequired & "</td>"
o=o& "<td>" & objItem.SID & "</td>"
o=o& "<td>" & objItem.SIDType & "</td>"
o=o& "<td>" & objItem.Status & "</td>"
o=o& "</tr>"
Next
on error goto 0
GetUsers = o
end function
Function getlcl(srvname)
Set objComputer = GetObject("WinNT://" & srvname & "/Administrators,group")
wscript.echo "Local Accounts on " & srvname
wscript.echo "-------------------------------------------------"
For Each objUser in objComputer.Members
Wscript.Echo vbTab & objUser.Name
Next
wscript.echo "-------------------------------------------------"
end Function
function GetBuiltInAccount(strComputer)
on error resume next
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
if err.number <> 0 then
GetBuiltInAccout = "Get Object WMI [[Fail]]: " & err.number & ":: " & err.description
err.clear
exit function
end if
on error goto 0
on error resume next
Set colAccounts = objWMIService.ExecQuery("Select * From Win32_UserAccount Where Domain = '" & strComputer & "'")
if err.number <> 0 then
GetBuiltInAccout = "WMI_ExecQuery [[Fail]]: " & err.number & ":: " & err.description
err.clear
exit function
end if
on error goto 0
on error resume next
For Each objAccount in colAccounts
if err.number <> 0 then
GetBuiltInAccout = "WMI_ExecQuery_ForEachAccount [[Fail]]: " & err.number & ":: " & err.description
wscript.echo "WMI_ExecQuery_ForEachAccount [[Fail]]: " & err.number & ":: " & err.description
err.clear
exit function
end if
on error goto 0
If Left (objAccount.SID, 6) = "S-1-5-" and Right(objAccount.SID, 4) = "-500" Then
GetBuiltInAccount = objAccount.Name
exit function
End If
Next
end function
Special instructions
For Domain servers:
Create a batch/cmd file (something like admins.cmd) containing the line below:
cscript admin.vbs /servers:list.txt
For Standalone server:
-Download CPAU.exe
Create a batch/cmd file (something like adminsNDC.cmd) conteninig the line below:
CPAU -u %COMPUTERNAME%\administrator -p mypassword -ex "cscript.exe Admins.vbs /servers:list.txt" -nowarn
-Local Admin report v1-
Instructions
For Domain servers:
1-Add the servers to be scaned into: "list.txt"
2-Run/create a scheduled task for "one" of the following files :
admins.cmd <-------> (you will get: |Hostname|User| Disabled |Locked |Expiration Date| Flags |BuiltIn |)
3-Check the html report(you can sent it to excel through IE)
For a Standalone server:
1-Add the server to be scaned into: "list.txt"
2-Edit the account name and password info into adminsNDC.cmd
3-Run adminsNDC.cmd <-------> (you will get: |Hostname|User| Disabled |Locked |Expiration Date| Flags |BuiltIn |)
3-Check the html report
After getting a report of the servers and accounts, this script could be used to perform password's update.
Option Explicit
Dim strExcelPath, objExcel, objSheet, intRow, strUserDN, strPassword, comp
Dim objUser
' Spreadsheet file.
strExcelPath = "c:\List.xls"
' Bind to Excel object.
On Error Resume Next
Set objExcel = CreateObject("Excel.Application")
If (Err.Number <> 0) Then
On Error GoTo 0
Wscript.Echo "Excel application not found."
Wscript.Quit
End If
On Error GoTo 0
' Open spreadsheet.
On Error Resume Next
objExcel.Workbooks.Open strExcelPath
If (Err.Number <> 0) Then
On Error GoTo 0
Wscript.Echo "Spreadsheet cannot be opened: " & strExcelPath
Wscript.Quit
End If
On Error GoTo 0
' Bind to worksheet.
Set objSheet = objExcel.ActiveWorkbook.Worksheets(1)
intRow = 2
Do While objSheet.Cells(intRow, 1).Value <> ""
comp = objSheet.Cells(intRow, 1).Value
strUserDN = objSheet.Cells(intRow, 2).Value
strPassword = objSheet.Cells(intRow, 3).Value
On Error Resume Next
Set objuser = GetObject ("WinNT://" & comp & "/" & strUserDN & ",user")
If (Err.Number <> 0) Then
On Error GoTo 0
Wscript.Echo "Data NOT found: "
Else
objUser.SetPassword strPassword
If (Err.Number <> 0) Then
On Error GoTo 0
Wscript.Echo "Password NOT set for: " & strUserDN
Else
End If
End If
intRow = intRow + 1
Loop
' Close the workbook.
objExcel.ActiveWorkbook.Close
' Quit Excel.
objExcel.Application.Quit
Wscript.Echo "Done"

Resources