Created
August 29, 2018 01:04
-
-
Save haginara/9b81104a202e985ad02dcbb05ed4e1f0 to your computer and use it in GitHub Desktop.
Windows Update Scripts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import argparse | |
import win32com | |
import win32com.client | |
import os | |
import re | |
try: | |
import _winreg as winreg | |
except ImportError: | |
import winreg | |
updates_pattern = re.compile(r'KB+\d+') | |
def check_restart(): | |
#https://blogs.msdn.microsoft.com/hansr/2006/02/17/how-to-detect-if-a-reboot-is-needed-after-installing-a-patch/ | |
path = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\WindowsUpdate\\Auto Update" | |
hkey = winreg.OpenKeyEx(winreg.HKEY_LOCAL_MACHINE, path, 0, winreg.KEY_READ | winreg.KEY_WOW64_64KEY) | |
try: | |
key = winreg.OpenKey(hkey, "RebootRequired") | |
if key: | |
print("[+] Reboot required by registry") | |
os.system("shutdown -t 30 -r -f") | |
except Exceptiona as e: | |
print("[+] Reboot doesn't required") | |
pass | |
def main(): | |
parser = argparse.ArgumentParser() | |
parser.add_argument("--restart-required", action='store_true') | |
options = parser.parse_args() | |
if options.restart_required: | |
check_restart() | |
return | |
wua = win32com.client.Dispatch("Microsoft.Update.Session") | |
print("[+] Find updates available") | |
update_seeker = wua.CreateUpdateSearcher() | |
search_available = update_seeker.Search("IsInstalled=0 and Type='Software'") | |
updates = win32com.client.Dispatch("Microsoft.Update.UpdateColl") | |
for update_available in search_available.Updates: | |
print("Name: {}".format(update_available)) | |
updates.Add(update_available) | |
print("[+] Download available updates") | |
downloader = wua.CreateUpdateDownloader() | |
downloader.Updates = updates | |
if updates.Count != 0: | |
downloader.Download() | |
updatesToInstall = win32com.client.Dispatch("Microsoft.Update.UpdateColl") | |
rebootMayBeRequired = False | |
for update in search_available.Updates: | |
if update.IsDownloaded == True: | |
updatesToInstall.Add(update) | |
if update.InstallationBehavior.RebootBehavior > 0: | |
rebootMayBeRequired = True | |
print("[+] Install updates") | |
installer = wua.CreateUpdateInstaller() | |
installer.Updates = updatesToInstall | |
if updatesToInstall.Count != 0: | |
result = installer.Install() | |
print("[+] ResultCode: {}".format(result.ResultCode)) | |
for idx, update in enumerate(updatesToInstall.Updates): | |
print("[+] {}: {}".format(update.Title, result.GetUpdateResult[i].ResultCode)) | |
if rebootMayBeRequired: | |
print("[+] Reboot Required") | |
os.system("shutdown -t 30 -r -f") | |
check_restart() | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment