Install security and critical updates in windows without reboot

Hi all,

Please refer attached procedure to install critical and security updates without reboot using windows built-in update functions. Script works well if run as “System User”


import os

vbs=r'''
Dim fso,logfile, iReboot, bMSReboot, appendout
logfile = "%s"    'Name of log file.
Const ForAppend = 8
Set fso = CreateObject("Scripting.FileSystemObject")
Dim WshShell: Set WshShell = WScript.CreateObject("WScript.Shell")
iReboot = 0
On Error Resume Next
Set appendout = fso.OpenTextFile(logfile, ForAppend, True)
WriteLog "Launched with do not reboot"

Set oSession = CreateObject("Microsoft.Update.Session")

Set updateSearcher = oSession.CreateupdateSearcher
If Err <> 0 Then
    WriteLog "Update Searcher not created" & Err.Description
    WScript.Quit
End If 

Set searchResult = updateSearcher.Search("IsInstalled=0 and Type='Software'")
If Err <> 0 Then
    WriteLog "Update Search function failed."&  Err.Description
    WScript.Quit
End If 

If searchResult.Updates.Count = 0 Then
    WriteLog "There are no applicable updates."
    WScript.Quit
End If

'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)
    Set objCategories = update.Categories
    strCatName = lcase(objCategories.Item(0).Name)

    If     strCatName = "security updates" Or _
        strCatName = "critical updates" Or _
        InStr(strCatName,"office") And     InStr(update.description,"security") Then 
    WriteLog "adding " & update.Title & " to download list."
        updatesToDownload.Add(update) 
    End If 
Next

'Downloading updates...
If updatestoDownload.count = 0 Then
    WriteLog "No critical or security patches found to download, quitting."
    WScript.Quit
End If
Set downloader = oSession.CreateUpdateDownloader() 

downloader.Updates = updatesToDownload
downloader.Download()

Set updatesToInstall = CreateObject("Microsoft.Update.UpdateColl")

'Creating collection of downloaded updates to install

For I = 0 To searchResult.Updates.Count-1
    set update = searchResult.Updates.Item(I)
    If update.IsDownloaded  Then
        WriteLog "adding " & update.Title & " to install list."
        updatesToInstall.Add(update)    
    End If
Next

WriteLog "Installing updates..."
Set installer = oSession.CreateUpdateInstaller()
installer.Updates = updatesToInstall
Set installationResult = installer.Install()

'Output results of install
WriteLog "Installation Result: " &    Code2Text(installationResult.ResultCode)
WriteLog  "Reboot Required: " & installationResult.RebootRequired 
bMSReboot = installationResult.RebootRequired
strMessage = "Listing of updates installed " & _
 "and individual installation results:"  & VbCrLf 

For I = 0 to updatesToInstall.Count - 1
    strMessage =  VbCrLf & strMessage & vbtab & updatesToInstall.Item(i).Title & _
    ": " & code2text(installationResult.GetUpdateResult(i).ResultCode) & vbNewLine

Next

WriteLog strMessage

If bMSReboot = False then 
    strmessage ="Done.  No reboot required"
Else
    If iReboot = 2 Then strmessage = "Done.  Logged on user, not rebooting computer"
    If iReboot = 0 Then strmessage = "Done.  Not rebooting computer"            
End If 

WriteLog strmessage



Sub WriteLog (message)
    message = now & vbTab &  message
    AppendOut.WriteLine message
End Sub  


Function Code2Text(iCode)
    If iCode = 2 Then 
        Code2Text = "Okay"
    Else
        Code2Text = "Failed"
    End If 
End Function 
'''

try:
    workdir=os.environ['PROGRAMDATA']+r'	emp'
    if not os.path.exists(workdir):
        os.mkdir(workdir)      
except:
    workdir=os.environ['SYTEMDRIVE']



logpath=workdir+r'\update_log.txt'
script =vbs % (logpath)

with open(workdir+r'\windowsupdate.vbs',"wb") as f :
    f.write(script)        

print os.popen('cscript.exe "'+workdir+'\windowsupdate.vbs"').read()

with open(logpath,"r") as fr :
    out=fr.read()        

print out

try:
    if os.path.isfile(workdir+r'\windowsupdate.vbs'):
        os.remove(workdir+r'\windowsupdate.vbs')

    if os.path.isfile(logpath):
        os.remove(logpath)
except: 
    pass





Sample output:

20170520-Install-security-and-critical-updates.json (5.71 KB)

Hi

Thank you for the script. I have tested it on a few assets and on most it works well.

I did pick up a problem on a few - this is the error that is displayed in the log. How can assist in testing & correcting this?

Microsoft (R) Windows Script Host Version 5.812 Copyright (C) Microsoft Corporation. All rights reserved.
Traceback (most recent call last): File “<string>”, line 126, in <module> IOError: [Errno 13] Permission denied: ‘C:\WINDOWS\TEMP\update_log.txt’
Best

Theuns

Hi @ITB_T

I will check this issue and update you.

Thanks

You can also use directly the patch procedure to select appropriate categories and configure the restart option under “Restart Control” tab.

https://help.comodo.com/topic-399-1-786-10976-Create-a-Custom-Procedure.html#cus_patch_proc

Ilker

Hi @ITB_T

Please refer initial post again. I have updated the script attachment as well as code content.

Let us know your feedback.

Thanks

we ran this today and encountered this error: it only happened on a couple machine.
Traceback (most recent call last): File “<string>”, line 2, in <module> File “C:\Program Files\COMODO\Comodo ITSM\lib\os.py”, line 425, in getitem return self.data[key.upper()] KeyError: ‘PROGRAMDATA’ error 2
Traceback (most recent call last): File “<string>”, line 126, in <module> IOError: [Errno 13] Permission denied: 'C:\WINDOWS\TEMP\update_log.txt thanks

Hi @hytekcomputers

Thank you for posting your comments with required error information. I have updated the initial post again. Please try now and let us know your feedback.

Hi,

I have tested the latest script - error below shows:
(thank you for assisting)

Microsoft (R) Windows Script Host Version 5.8 Copyright (C) Microsoft Corporation. All rights reserved. CScript Error: Can’t find script engine “VBScript” for script “C:\ProgramData emp\windowsupdate.vbs”.
Traceback (most recent call last): File “<string>”, line 134, in <module> IOError: [Errno 2] No such file or directory: ‘C:\ProgramData\ emp\update_log.txt’

Hi @ITB_T

Thank you for notifying us about the issue. We need more details to fix your issue. Our support team will reach out to you shortly.

Hi @ITB_T

Seems like VBscript settings has been corrupted in the error-ed device.

Please try applying following fix,

1.FIx The Dll File

a)Open Command Prompt and Run as administrator
b)Execute following commands
cd %windir%\system32
regsvr32 vbscript.dl

c)Try running script procedure again from portal

if the issue persist , please follow below section,

2.Check Registry Setting

a).Open Registry Editor in the error-ed system and navigate to the following key
HKCR\CLSID{B54F3741-5B07-11cf-A4B0-00AA004A55E8}\InprocServer32
b)The entry called (Default) should have a value of C:\Windows\system32\vbscript.dll.However, an old/corrupt antivirus may have set the value of (Default) to something different.
If the value of (Default) is not correct then double click it and change its value to C:\Windows\system32\vbscript.dll
c)Close the Registry Editor and restart the computer.
d)Try running script procedure again from portal

Let us know your feedback

Hi

how to download the code and do we need to save it as .vbs and run from command line as I am getting below error while executing the script.

X script: c: emp\windowsupdate.vbs
Line: 118
Char: 23
Error: Expected end of Statement
Code: 800A0401
Source: Microsoft VBscript compilation error.

Hello @Sunil

Just download the attached JSON file and kindly, refer the below link to import the JSON and execute it.
https://wiki.itarian.com/frontend/web/topic/how-to-import-a-procedure-and-execute-it

Thank you