private Task CheckWuAutoDownloadEnabledAsync(CancellationToken token) { token.ThrowIfCancellationRequested(); // Windows Update Automatic Download enabled (automatically downloading an update without notification beforehand)? // If so, it's best to disable this and deploy either POA (for Bronze durability clusters) // or enable VMSS automatic OS image upgrades for Silver+ durability clusters. // This is important to prevent unexpected, concurrent VM reboots due to Windows Updates. try { var wuLibAutoUpdates = new AutomaticUpdatesClass(); this.isWindowsUpdateAutoDownloadEnabled = wuLibAutoUpdates.ServiceEnabled && wuLibAutoUpdates.Settings.NotificationLevel == AutomaticUpdatesNotificationLevel.aunlScheduledInstallation; } catch (Exception e) when( e is COMException || e is InvalidOperationException || e is SecurityException || e is Win32Exception) { ObserverLogger.LogWarning( $"{AuStateUnknownMessage}{Environment.NewLine}{e}"); this.auStateUnknown = true; } return(Task.CompletedTask); }
public List <Metric> GetMetrics() { var session = new UpdateSession(); ISearchResult uResult; var updateChecker = new AutomaticUpdatesClass(); var results = new List <Metric>(); results.Add(new Metric("windows.updates.enabled", updateChecker.ServiceEnabled ? 1 : 0)); if (!updateChecker.ServiceEnabled) { return(results); } int totalUpdates = 0; int criticalUpdates = 0; int updatesNeedingReboot = 0; uResult = CheckForUpdates(session); if (uResult != null) { foreach (IUpdate5 uResultUpdate in uResult.Updates) { if (uResultUpdate == null) { continue; } if (!String.IsNullOrWhiteSpace(uResultUpdate.MsrcSeverity) && uResultUpdate.MsrcSeverity.Contains("Critical")) { criticalUpdates++; } totalUpdates++; if (uResultUpdate.RebootRequired) { updatesNeedingReboot++; } } } results.Add(new Metric("windows.updates.count", totalUpdates, tags: new Dictionary <string, string> { { "severity", "all" } })); results.Add(new Metric("windows.updates.count", criticalUpdates, tags: new Dictionary <string, string> { { "severity", "critical" } })); results.Add(new Metric("windows.updates.rebootcount", updatesNeedingReboot, tags: new Dictionary <string, string> { { "severity", "all" } })); return(results); }
/// <summary> /// This will disable the windows update on system. /// </summary> private void DisableWindowsUpdate() { CheckpointFileData fileData = this.ReadCheckpointFile(); DateTime initialTime = DateTime.Now; if (!fileData.lastAttemptedUpdateTime.Equals(_checkpointFileDefaultDateTime)) { initialTime = fileData.lastAttemptedUpdateTime; } long timeToLive = (long)((fileData.schedulingDateTime - initialTime) + TimeSpan.FromDays(1)).TotalMinutes; if (!this._serviceSettings.DisableWindowsUpdates) { _eventSource.InfoMessage("Not disabling automatic windows updates."); return; } _eventSource.InfoMessage("Disabling automatic windows updates."); do { string msg = "Not able to disable the 'Windows Updates'. "; try { WindowsAutoUpdateUtility auUtility = new WindowsAutoUpdateUtility(); if (auUtility.IsWindowsServer2012R2OrLower()) { _eventSource.InfoMessage("Detected OS version is Windows Server 2012R2 or lower"); AutomaticUpdatesClass updates = new AutomaticUpdatesClass(); _eventSource.InfoMessage("Current automatic windows updates notification level {0}.", updates.Settings.NotificationLevel); auUtility.DisableAUThroughWUApi(updates); } else { _eventSource.InfoMessage("Detected OS version is higher than Windows Server 2012R2"); _eventSource.InfoMessage("Current AU registry values are {0}", auUtility.LogCurrentAUValues()); auUtility.SetAUOptions(); _eventSource.InfoMessage("New AU registry values are {0}", auUtility.LogCurrentAUValues()); } string updateMsg = "Windows Update policy has been configured to Notify before Download"; this._nodeAgentSfUtility.ReportHealth(WUOperationSetting, updateMsg, HealthState.Ok, timeToLive, TimeSpan.FromMinutes(this._serviceSettings.OperationTimeOutInMinutes)); return; } catch (Exception e) { msg = string.Format(msg + "Failing with exception : {0}", e); } _eventSource.WarningMessage(msg); this._nodeAgentSfUtility.ReportHealth(WUOperationSetting, msg, HealthState.Warning, -1, TimeSpan.FromMinutes(this._serviceSettings.OperationTimeOutInMinutes)); this._helper.WaitOnTask(Task.Delay(TimeSpan.FromMinutes(WaitTimeInMinutes)), this._cancellationToken); } while (true); }
private bool SetWindowsUpdate(bool enable) { if (OSVersion.FriendlyName().Contains("10")) { //Stop per Windows Service on windows 10 ServiceController service = new ServiceController("wuauserv"); try { TimeSpan timeout = TimeSpan.FromMilliseconds(500); if (enable) { service.Start(); //service.WaitForStatus(ServiceControllerStatus.Running, timeout); } else { service.Stop(); //service.WaitForStatus(ServiceControllerStatus.Stopped, timeout); } Logger.Log(String.Format("Set windows update to {0}", enable)); return(true); } catch { return(false); } } //Use Automatic Update Class try { var auc = new AutomaticUpdatesClass(); if (enable) { auc.Resume(); } else { auc.Pause(); } Logger.Log(String.Format("Set windows update to {0}", enable)); return(true); } catch (Exception) { return(false); } }
public static bool DisableAutomaticWindowsUpdates() { try { var auc = new AutomaticUpdatesClass(); auc.Settings.NotificationLevel = AutomaticUpdatesNotificationLevel.aunlDisabled; auc.Settings.Save(); return true; } catch (Exception e) { Logger.Log("Unable to disable Windows Automatic Updates. Error: {0}", LogLevel.Info, e.Message); return false; } }
public static bool DisableAutomaticWindowsUpdates() { try { var auc = new AutomaticUpdatesClass(); auc.Settings.NotificationLevel = AutomaticUpdatesNotificationLevel.aunlDisabled; auc.Settings.Save(); return(true); } catch (Exception e) { Logger.Log("Unable to disable Windows Automatic Updates. Error: {0}", LogLevel.Info, e.Message); return(false); } }
static void SetNotificationLevel(string newval) { AutomaticUpdatesClass au = new AutomaticUpdatesClass(); if (au.Settings.ReadOnly) { Console.WriteLine("ERROR: Settings currently read only, please run this utility as an administrator."); return; } switch (newval.ToLower()) { case "disabled": au.Settings.NotificationLevel = AutomaticUpdatesNotificationLevel.aunlDisabled; break; case "notconfigured": au.Settings.NotificationLevel = AutomaticUpdatesNotificationLevel.aunlNotConfigured; break; case "notifybeforedownload": au.Settings.NotificationLevel = AutomaticUpdatesNotificationLevel.aunlNotifyBeforeDownload; break; case "notifybeforeinstall": au.Settings.NotificationLevel = AutomaticUpdatesNotificationLevel.aunlNotifyBeforeInstallation; break; case "scheduledinstall": au.Settings.NotificationLevel = AutomaticUpdatesNotificationLevel.aunlScheduledInstallation; break; default: Console.WriteLine("ERROR: Invalid Notification Level Specified (Options: Disabled, NotConfigured, NotifyBeforeDownload, NotifyBeforeInstall, ScheduledInstall)"); break; } try { au.Settings.Save(); Console.WriteLine("Windows Update Notification Level: " + newval); } catch (Exception ex) { Console.WriteLine("ERROR: " + ex.Message); } }
/// <summary> /// This will disable the windows update on system. /// </summary> private void DisableWindowsUpdate() { if (!this._serviceSettings.DisableWindowsUpdates) { _eventSource.InfoMessage("Not disabling automatic windows updates."); return; } _eventSource.InfoMessage("Disabling automatic windows updates."); do { string msg = "Not able to disable the 'Windows Updates'. "; try { WindowsAutoUpdateUtility auUtility = new WindowsAutoUpdateUtility(); if (auUtility.IsWindowsServer2012R2OrLower()) { _eventSource.InfoMessage("Detected OS version is Windows Server 2012R2 or lower"); AutomaticUpdatesClass updates = new AutomaticUpdatesClass(); _eventSource.InfoMessage("Current automatic windows updates notification level {0}.", updates.Settings.NotificationLevel); auUtility.DisableAUThroughWUApi(updates); } else { _eventSource.InfoMessage("Detected OS version is higher than Windows Server 2012R2"); _eventSource.InfoMessage("Current AU registry values are {0}", auUtility.LogCurrentAUValues()); auUtility.SetAUOptions(); _eventSource.InfoMessage("New AU registry values are {0}", auUtility.LogCurrentAUValues()); } return; } catch (Exception e) { msg = string.Format(msg + "Failing with exception : {0}", e); } _eventSource.WarningMessage(msg); this._nodeAgentSfUtility.ReportHealth("WindowsUpdateOperationResult", msg, HealthState.Warning, -1, TimeSpan.FromMinutes(this._serviceSettings.OperationTimeOutInMinutes)); this._helper.WaitOnTask(Task.Delay(TimeSpan.FromMinutes(WaitTimeInMinutes)), this._cancellationToken); } while (true); }
private bool SetWindowsUpdate(bool enable) { if (OSVersion.FriendlyName().Contains("10")) { //Stop per Windows Service on windows 10 ServiceController service = new ServiceController("wuauserv"); try { TimeSpan timeout = TimeSpan.FromMilliseconds(500); if (enable) { service.Start(); //service.WaitForStatus(ServiceControllerStatus.Running, timeout); } else { service.Stop(); //service.WaitForStatus(ServiceControllerStatus.Stopped, timeout); } Logger.Log(String.Format("Set windows update to {0}", enable)); return true; } catch { return false; } } //Use Automatic Update Class try { var auc = new AutomaticUpdatesClass(); if (enable) auc.Resume(); else auc.Pause(); Logger.Log(String.Format("Set windows update to {0}", enable)); return true; } catch (Exception) { return false; } }
private bool SetWindowsUpdate(bool enable) { try { var auc = new AutomaticUpdatesClass(); if(enable) auc.Resume(); else auc.Pause(); Logger.Log(String.Format("Set windows update to {0}",enable)); return true; } catch (Exception) { return false; } }
// Token: 0x06000004 RID: 4 RVA: 0x00002528 File Offset: 0x00000728 public OptInStatus SetMicrosoftUpdateOptinStatus(OptInStatus optIn, string cabLocation) { bool flag = optIn == OptInStatus.RequestDisabled || optIn == OptInStatus.RequestNotifyDownload || optIn == OptInStatus.RequestNotifyInstall || optIn == OptInStatus.RequestScheduled; try { IWindowsUpdateAgentInfo windowsUpdateAgentInfo = new WindowsUpdateAgentInfoClass(); string text = windowsUpdateAgentInfo.GetInfo("ProductVersionString") as string; if (string.IsNullOrEmpty(text)) { if (flag) { UpdateSvcEventLogger.LogEvent(AntispamUpdateServiceEventLogConstants.Tuple_MuOpt, null, new string[0]); } if (this.ConsoleDiagnostics) { Console.WriteLine("Unable to determine WUA Version"); } return(OptInStatus.NotConfigured); } Version v = new Version(text); if (v < HygieneUpdate.AgentMinVersion) { if (flag) { UpdateSvcEventLogger.LogEvent(AntispamUpdateServiceEventLogConstants.Tuple_MuOpt, null, new string[0]); } if (this.ConsoleDiagnostics) { Console.WriteLine("Out of date client"); } return(OptInStatus.NotConfigured); } } catch (COMException) { if (flag) { UpdateSvcEventLogger.LogEvent(AntispamUpdateServiceEventLogConstants.Tuple_MuOpt, null, new string[0]); } if (this.ConsoleDiagnostics) { Console.WriteLine("Unable to determine Windows Update Agent version"); } return(OptInStatus.NotConfigured); } try { IUpdateServiceManager updateServiceManager = new UpdateServiceManagerClass(); foreach (object obj in updateServiceManager.Services) { IUpdateService updateService = (IUpdateService)obj; if (this.ConsoleDiagnostics) { Console.WriteLine("Service {0}: {1} {2}", updateService.ServiceID, updateService.IsRegisteredWithAU, updateService.IsManaged); } if ((string.Compare("7971f918-a847-4430-9279-4a52d1efe18d", updateService.ServiceID, StringComparison.OrdinalIgnoreCase) == 0 && updateService.IsRegisteredWithAU) || updateService.IsManaged) { if (this.ConsoleDiagnostics) { Console.WriteLine("Microsoft Update already registered."); } return(OptInStatus.Configured); } } if (!flag) { return(OptInStatus.NotConfigured); } if (string.IsNullOrEmpty(cabLocation)) { UpdateSvcEventLogger.LogEvent(AntispamUpdateServiceEventLogConstants.Tuple_MuOpt, null, new string[0]); if (this.ConsoleDiagnostics) { Console.WriteLine("Invalid CAB location"); } } updateServiceManager.AddService("7971f918-a847-4430-9279-4a52d1efe18d", cabLocation); updateServiceManager.RegisterServiceWithAU("7971f918-a847-4430-9279-4a52d1efe18d"); IAutomaticUpdates automaticUpdates = new AutomaticUpdatesClass(); if (!automaticUpdates.Settings.ReadOnly && automaticUpdates.Settings.NotificationLevel == null) { automaticUpdates.Settings.NotificationLevel = optIn; automaticUpdates.Settings.ScheduledInstallationDay = 0; automaticUpdates.Settings.Save(); } } catch (COMException ex) { if (flag) { UpdateSvcEventLogger.LogEvent(AntispamUpdateServiceEventLogConstants.Tuple_MuOptFail, null, new string[] { ex.Message }); } if (this.ConsoleDiagnostics) { Console.WriteLine("Failed: {0}", ex.Message); } return(OptInStatus.NotConfigured); } catch (InvalidCastException ex2) { UpdateSvcEventLogger.LogEvent(AntispamUpdateServiceEventLogConstants.Tuple_MuGetFail, null, new string[] { ex2.Message }); if (this.ConsoleDiagnostics) { Console.WriteLine("Failed: {0}", ex2.Message); } return(OptInStatus.NotConfigured); } return(OptInStatus.Configured); }
static void SetScheduleWU(string day, int hour) { //AutomaticUpdates au = new AutomaticUpdates(); AutomaticUpdatesClass au = new AutomaticUpdatesClass(); if (au.Settings.ReadOnly) { Console.WriteLine("ERROR: Settings currently read only, please run this utility as an administrator."); return; } switch (day.ToLower()) { case "all": au.Settings.ScheduledInstallationDay = AutomaticUpdatesScheduledInstallationDay.ausidEveryDay; break; case "mon": au.Settings.ScheduledInstallationDay = AutomaticUpdatesScheduledInstallationDay.ausidEveryMonday; break; case "tue": au.Settings.ScheduledInstallationDay = AutomaticUpdatesScheduledInstallationDay.ausidEveryTuesday; break; case "wed": au.Settings.ScheduledInstallationDay = AutomaticUpdatesScheduledInstallationDay.ausidEveryWednesday; break; case "thu": au.Settings.ScheduledInstallationDay = AutomaticUpdatesScheduledInstallationDay.ausidEveryThursday; break; case "fri": au.Settings.ScheduledInstallationDay = AutomaticUpdatesScheduledInstallationDay.ausidEveryFriday; break; case "sat": au.Settings.ScheduledInstallationDay = AutomaticUpdatesScheduledInstallationDay.ausidEverySaturday; break; case "sun": au.Settings.ScheduledInstallationDay = AutomaticUpdatesScheduledInstallationDay.ausidEverySunday; break; default: Console.WriteLine("ERROR: Invalid Day Specified (Options: Mon, Tue, Wed, Thu, Fri, Sat, Sun)"); return; } if (hour >= 0 && hour <= 23) { au.Settings.ScheduledInstallationTime = hour; } else { Console.WriteLine("ERROR: Invalid Hour Specified (Options: 0-23)"); return; } try { au.Settings.Save(); Console.WriteLine("Windows Update Schedule: " + day + " @ " + hour.ToString()); } catch (Exception ex) { Console.WriteLine("ERROR: " + ex.Message); } }
/// <summary> /// //Loading the main window /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void MainWindow_Load(object sender, EventArgs e) { try { //UpdateSessionClass uSession = new UpdateSessionClass(); //IUpdateSearcher uSearcher = uSession.CreateUpdateSearcher(); //ISearchResult uResult = uSearcher.Search("IsInstalled=0 and Type='Software'"); //foreach (IUpdate update in uResult.Updates) //{ // Console.WriteLine(update.Title); //} if (SystemVolumChanger.IsMuted()) { SendMessage(this.Handle, WM_APPCOMMAND, this.Handle, (IntPtr)APPCOMMAND_VOLUME_MUTE); SistemVolumChanger.SetVolume(50); } //string subKey = @"\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate"; //using (RegistryKey key = Registry.LocalMachine.OpenSubKey(subKey, true)) //{ // key.GetValue("AUoptions"); //} AutomaticUpdatesClass auc = new AutomaticUpdatesClass(); auc.Settings.NotificationLevel = AutomaticUpdatesNotificationLevel.aunlNotifyBeforeInstallation; auc.Settings.Save(); auc.Settings.NotificationLevel.ToString(); //AutomaticUpdates auc = new AutomaticUpdates(); //bool active = auc.ServiceEnabled; //SendMessage(this.Handle, WM_APPCOMMAND, this.Handle, (IntPtr)APPCOMMAND_VOLUME_MUTE); //SendMessage(this.Handle, WM_APPCOMMAND, this.Handle, (IntPtr)APPCOMMAND_VOLUME_UP); int ts = Convert.ToInt32((DateTime.Now.AddHours(2) - DateTime.Now).TotalSeconds.ToString()); this.Text = (ConfigSettings.ClientName.ToUpper() == clientName) ? "Activei" : "GearHead Connect"; this.Icon = (ConfigSettings.ClientName.ToUpper() == clientName) ? Properties.Resources.Activei : Properties.Resources.NG_Icon; picboxload.Image = (ConfigSettings.ClientName.ToUpper() == clientName) ? Activei.Properties.Resources.loader : Activei.Properties.Resources.gearhead_loader; this.Width = Screen.PrimaryScreen.WorkingArea.Width; this.Height = Screen.PrimaryScreen.WorkingArea.Height; pnlLoading.Width = this.Width; this.Location = new Point(0, 0); pnlLoading.Location = new Point(0, this.Height / 3); this.DoubleBuffered = true; //routerAuthenticated = routerAuthentication("admin", "password"); NetworkChange.NetworkAvailabilityChanged += new NetworkAvailabilityChangedEventHandler(NetworkChange_NetworkAvailabilityChanged); NetworkChange.NetworkAddressChanged += new NetworkAddressChangedEventHandler(NetworkChange_NetworkAddressChanged); //MainWindow.ShowInterfaceSummary(); isNetworkAvailable = System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable(); //Take Router Back up string hostName = string.Empty; if (GetPublicIPPingSuccessCount("google.com") == 1) { hostName = GetDefaultGateway().ToString(); CreateTelnetBatFile(hostName); RouterBackupusingTelnetClient(hostName, 23); } //else //{ // ErrorTracker.WriteLog("Bat file not created ..."); // RouterBackupusingTelnetClient(GetDefaultGateway().ToString(), 23); //} SetURl(); //checkIntermittentWIFI(); } catch (Exception ex) { ErrorTracker.WriteErrorLog("MainWindow.cs", "MainWindow_Load", "", ex.Message, ex.StackTrace, "ERROR"); } }
static void Main(string[] args) { UpdateSession session = new UpdateSession(); ISearchResult uResult; AutomaticUpdatesClass updateChecker = new AutomaticUpdatesClass(); Console.WriteLine("Service enabled?" + updateChecker.ServiceEnabled); int attempts = 5; while (!updateChecker.ServiceEnabled && attempts >= 0){ attempts--; updateChecker.EnableService(); Thread.Sleep(2000); } Boolean moreUpdates = true; while (moreUpdates) { uResult = CheckForUpdates(session); UpdateCollection toInstallAutomatically = getAutoUpdates(uResult); if (toInstallAutomatically.Count > 0) { IInstallationResult installationRes = installUpdates(session, toInstallAutomatically); if (installationRes.RebootRequired) { Console.WriteLine("Rebooting to finish installation!"); moreUpdates = false; System.Diagnostics.Process.Start("ShutDown", "/r"); } } else { moreUpdates = false; System.Console.WriteLine("Updates Complete! Press a key to continue."); System.Console.ReadKey(); } } }
private bool SetWindowsUpdate(bool enable) { try { Logger.Log("Connecting to windows update"); var auc = new AutomaticUpdatesClass(); if(enable) auc.Resume(); else auc.Pause(); Logger.Log(string.Format("Set windows update to {0}",enable)); return true; } catch (Exception e) { Logger.Log(e, string.Format("Error configuring windows update")); return false; } }