diff --git a/salt/modules/win_task.py b/salt/modules/win_task.py index 50450e906fee..4f7e7a5c5d93 100644 --- a/salt/modules/win_task.py +++ b/salt/modules/win_task.py @@ -10,16 +10,16 @@ You can list all tasks, folders, triggers, and actions. ''' # Import Python libs -from __future__ import absolute_import, unicode_literals, print_function +from __future__ import absolute_import, print_function, unicode_literals +from datetime import datetime import logging import time -from datetime import datetime # Import Salt libs import salt.utils.platform import salt.utils.winapi -# Import 3rd-party libraries +# Import 3rd Party Libraries try: import pythoncom import win32com.client @@ -155,7 +155,8 @@ 0x41306: 'Task was terminated by the user', 0x8004130F: 'Credentials became corrupted', 0x8004131F: 'An instance of this task is already running', - 0x800704DD: 'The service is not available (Run only when logged in?)', + 0x800704DD: 'The service is not available (Run only when logged ' + 'in?)', 0x800710E0: 'The operator or administrator has refused the request', 0xC000013A: 'The application terminated as a result of CTRL+C', 0xC06D007E: 'Unknown software exception'} @@ -169,7 +170,7 @@ def __virtual__(): if not HAS_DEPENDENCIES: log.warning('Could not load dependencies for %s', __virtualname__) return __virtualname__ - return (False, "Module win_task: module only works on Windows systems") + return False, 'Module win_task: module only works on Windows systems' def _get_date_time_format(dt_string): @@ -302,7 +303,8 @@ def _save_task_definition(name, except pythoncom.com_error as error: hr, msg, exc, arg = error.args # pylint: disable=W0633 - fc = {-2147024773: 'The filename, directory name, or volume label syntax is incorrect', + fc = {-2147024773: 'The filename, directory name, or volume label ' + 'syntax is incorrect', -2147024894: 'The system cannot find the file specified', -2147216615: 'Required element or attribute missing', -2147216616: 'Value incorrectly formatted or out of range', @@ -321,18 +323,25 @@ def list_tasks(location='\\'): r''' List all tasks located in a specific location in the task scheduler. - :param str location: A string value representing the folder from which you - want to list tasks. Default is '\\' which is the root for the task - scheduler (C:\Windows\System32\tasks). + Args: + + location (str): + A string value representing the folder from which you want to list + tasks. Default is ``\`` which is the root for the task scheduler + (``C:\Windows\System32\tasks``). - :return: Returns a list of tasks. - :rtype: list + Returns: + list: Returns a list of tasks CLI Example: .. code-block:: bash + # List all tasks in the default location salt 'minion-id' task.list_tasks + + # List all tasks in the Microsoft\XblGameSave Directory + salt 'minion-id' task.list_tasks Microsoft\XblGameSave ''' # Create the task service object with salt.utils.winapi.Com(): @@ -354,18 +363,25 @@ def list_folders(location='\\'): r''' List all folders located in a specific location in the task scheduler. - :param str location: A string value representing the folder from which you - want to list tasks. Default is '\\' which is the root for the task - scheduler (C:\Windows\System32\tasks). + Args: + + location (str): + A string value representing the folder from which you want to list + tasks. Default is ``\`` which is the root for the task scheduler + (``C:\Windows\System32\tasks``). - :return: Returns a list of folders. - :rtype: list + Returns: + list: Returns a list of folders. CLI Example: .. code-block:: bash + # List all folders in the default location salt 'minion-id' task.list_folders + + # List all folders in the Microsoft directory + salt 'minion-id' task.list_folders Microsoft ''' # Create the task service object with salt.utils.winapi.Com(): @@ -387,20 +403,29 @@ def list_triggers(name, location='\\'): r''' List all triggers that pertain to a task in the specified location. - :param str name: The name of the task for which list triggers. + Args: - :param str location: A string value representing the location of the task - from which to list triggers. Default is '\\' which is the root for the - task scheduler (C:\Windows\System32\tasks). + name (str): + The name of the task for which list triggers. - :return: Returns a list of triggers. - :rtype: list + location (str): + A string value representing the location of the task from which to + list triggers. Default is ``\`` which is the root for the task + scheduler (``C:\Windows\System32\tasks``). + + Returns: + list: Returns a list of triggers. CLI Example: .. code-block:: bash + # List all triggers for a task in the default location salt 'minion-id' task.list_triggers + + # List all triggers for the XblGameSaveTask in the Microsoft\XblGameSave + # location + salt '*' task.list_triggers XblGameSaveTask Microsoft\XblGameSave ''' # Create the task service object with salt.utils.winapi.Com(): @@ -423,20 +448,29 @@ def list_actions(name, location='\\'): r''' List all actions that pertain to a task in the specified location. - :param str name: The name of the task for which list actions. + Args: + + name (str): + The name of the task for which list actions. - :param str location: A string value representing the location of the task - from which to list actions. Default is '\\' which is the root for the - task scheduler (C:\Windows\System32\tasks). + location (str): + A string value representing the location of the task from which to + list actions. Default is ``\`` which is the root for the task + scheduler (``C:\Windows\System32\tasks``). - :return: Returns a list of actions. - :rtype: list + Returns: + list: Returns a list of actions. CLI Example: .. code-block:: bash + # List all actions for a task in the default location salt 'minion-id' task.list_actions + + # List all actions for the XblGameSaveTask in the Microsoft\XblGameSave + # location + salt 'minion-id' task.list_actions XblGameSaveTask Microsoft\XblGameSave ''' # Create the task service object with salt.utils.winapi.Com(): @@ -465,29 +499,34 @@ def create_task(name, Create a new task in the designated location. This function has many keyword arguments that are not listed here. For additional arguments see: - - :py:func:`edit_task` - - :py:func:`add_action` - - :py:func:`add_trigger` + - :py:func:`edit_task` + - :py:func:`add_action` + - :py:func:`add_trigger` - :param str name: The name of the task. This will be displayed in the task - scheduler. + Args: - :param str location: A string value representing the location in which to - create the task. Default is '\\' which is the root for the task - scheduler (C:\Windows\System32\tasks). + name (str): + The name of the task. This will be displayed in the task scheduler. - :param str user_name: The user account under which to run the task. To - specify the 'System' account, use 'System'. The password will be - ignored. + location (str): + A string value representing the location in which to create the + task. Default is ``\`` which is the root for the task scheduler + (``C:\Windows\System32\tasks``). - :param str password: The password to use for authentication. This should set - the task to run whether the user is logged in or not, but is currently - not working. + user_name (str): + The user account under which to run the task. To specify the + 'System' account, use 'System'. The password will be ignored. - :param bool force: If the task exists, overwrite the existing task. + password (str): + The password to use for authentication. This should set the task to + run whether the user is logged in or not, but is currently not + working. - :return: True if successful, False if unsuccessful - :rtype: bool + force (bool): + If the task exists, overwrite the existing task. + + Returns: + bool: ``True`` if successful, otherwise ``False`` CLI Example: @@ -547,35 +586,41 @@ def create_task_from_xml(name, r''' Create a task based on XML. Source can be a file or a string of XML. - :param str name: The name of the task. This will be displayed in the task - scheduler. + Args: - :param str location: A string value representing the location in which to - create the task. Default is '\\' which is the root for the task - scheduler (C:\Windows\System32\tasks). + name (str): + The name of the task. This will be displayed in the task scheduler. - :param str xml_text: A string of xml representing the task to be created. - This will be overridden by `xml_path` if passed. + location (str): + A string value representing the location in which to create the + task. Default is ``\`` which is the root for the task scheduler + (``C:\Windows\System32\tasks``). - :param str xml_path: The path to an XML file on the local system containing - the xml that defines the task. This will override `xml_text` + xml_text (str): + A string of xml representing the task to be created. This will be + overridden by ``xml_path`` if passed. - :param str user_name: The user account under which to run the task. To - specify the 'System' account, use 'System'. The password will be - ignored. + xml_path (str): + The path to an XML file on the local system containing the xml that + defines the task. This will override ``xml_text`` - :param str password: The password to use for authentication. This should set - the task to run whether the user is logged in or not, but is currently - not working. + user_name (str): + The user account under which to run the task. To specify the + 'System' account, use 'System'. The password will be ignored. - :return: True if successful, False if unsuccessful - :rtype: bool + password (str): + The password to use for authentication. This should set the task to + run whether the user is logged in or not, but is currently not + working. + + Returns: + bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash - salt 'minion-id' task.create_task_from_xml xml_path=C:\task.xml + salt '*' task.create_task_from_xml xml_path=C:\task.xml ''' # Check for existing task if name in list_tasks(location): @@ -644,15 +689,19 @@ def create_folder(name, location='\\'): r''' Create a folder in which to create tasks. - :param str name: The name of the folder. This will be displayed in the task - scheduler. + Args: - :param str location: A string value representing the location in which to - create the folder. Default is '\\' which is the root for the task - scheduler (C:\Windows\System32\tasks). + name (str): + The name of the folder. This will be displayed in the task + scheduler. - :return: True if successful, False if unsuccessful - :rtype: bool + location (str): + A string value representing the location in which to create the + folder. Default is ``\`` which is the root for the task scheduler + (``C:\Windows\System32\tasks``). + + Returns: + bool: ``True`` if successful, otherwise ``False`` CLI Example: @@ -714,154 +763,174 @@ def edit_task(name=None, r''' Edit the parameters of a task. Triggers and Actions cannot be edited yet. - :param str name: The name of the task. This will be displayed in the task - scheduler. - - :param str location: A string value representing the location in which to - create the task. Default is '\\' which is the root for the task - scheduler (C:\Windows\System32\tasks). - - :param str user_name: The user account under which to run the task. To - specify the 'System' account, use 'System'. The password will be - ignored. + Args: - :param str password: The password to use for authentication. This should set - the task to run whether the user is logged in or not, but is currently - not working. + name (str): + The name of the task. This will be displayed in the task scheduler. + + location (str): + A string value representing the location in which to create the + task. Default is ``\`` which is the root for the task scheduler + (``C:\Windows\System32\tasks``). - .. note:: - The combination of user_name and password determine how the task runs. - For example, if a username is passed without at password the task will - only run when the user is logged in. If a password is passed as well - the task will run whether the user is logged on or not. If you pass - 'System' as the username the task will run as the system account (the - password parameter is ignored. - - :param str description: A string representing the text that will be - displayed in the description field in the task scheduler. - - :param bool enabled: A boolean value representing whether or not the task is - enabled. - - :param bool hidden: A boolean value representing whether or not the task is - hidden. - - :param bool run_if_idle: Boolean value that indicates that the Task - Scheduler will run the task only if the computer is in an idle state. - - :param str idle_duration: A value that indicates the amount of time that the - computer must be in an idle state before the task is run. Valid values - are: - - - 1 minute - - 5 minutes - - 10 minutes - - 15 minutes - - 30 minutes - - 1 hour - - :param str idle_wait_timeout: A value that indicates the amount of time that - the Task Scheduler will wait for an idle condition to occur. Valid - values are: - - - Do not wait - - 1 minute - - 5 minutes - - 10 minutes - - 15 minutes - - 30 minutes - - 1 hour - - 2 hours - - :param bool idle_stop_on_end: Boolean value that indicates that the Task - Scheduler will terminate the task if the idle condition ends before the - task is completed. - - :param bool idle_restart: Boolean value that indicates whether the task is - restarted when the computer cycles into an idle condition more than - once. - - :param bool ac_only: Boolean value that indicates that the Task Scheduler - will launch the task only while on AC power. - - :param bool stop_if_on_batteries: Boolean value that indicates that the task - will be stopped if the computer begins to run on battery power. - - :param bool wake_to_run: Boolean value that indicates that the Task - Scheduler will wake the computer when it is time to run the task. - - :param bool run_if_network: Boolean value that indicates that the Task - Scheduler will run the task only when a network is available. - - :param guid network_id: GUID value that identifies a network profile. - - :param str network_name: Sets the name of a network profile. The name is - used for display purposes. - - :param bool allow_demand_start: Boolean value that indicates that the task - can be started by using either the Run command or the Context menu. - - :param bool start_when_available: Boolean value that indicates that the Task - Scheduler can start the task at any time after its scheduled time has - passed. - - :param restart_every: A value that specifies the interval between task - restart attempts. Valid values are: - - - False (to disable) - - 1 minute - - 5 minutes - - 10 minutes - - 15 minutes - - 30 minutes - - 1 hour - - 2 hours - - :param int restart_count: The number of times the Task Scheduler will - attempt to restart the task. Valid values are integers 1 - 999. - - :param execution_time_limit: The amount of time allowed to complete the - task. Valid values are: - - - False (to disable) - - 1 hour - - 2 hours - - 4 hours - - 8 hours - - 12 hours - - 1 day - - 3 days - - :param bool force_stop: Boolean value that indicates that the task may be - terminated by using TerminateProcess. - - :param delete_after: The amount of time that the Task Scheduler will - wait before deleting the task after it expires. Requires a trigger with - an expiration date. Valid values are: - - - False (to disable) - - Immediately - - 30 days - - 90 days - - 180 days - - 365 days - - :param str multiple_instances: Sets the policy that defines how the Task - Scheduler deals with multiple instances of the task. Valid values are: - - - Parallel - - Queue - - No New Instance - - Stop Existing - - :return: True if successful, False if unsuccessful - :rtype: bool + user_name (str): + The user account under which to run the task. To specify the + 'System' account, use 'System'. The password will be ignored. + + password (str): + The password to use for authentication. This should set the task to + run whether the user is logged in or not, but is currently not + working. + + .. note:: + + The combination of user_name and password determine how the + task runs. For example, if a username is passed without at + password the task will only run when the user is logged in. If a + password is passed as well the task will run whether the user is + logged on or not. If you pass 'System' as the username the task + will run as the system account (the password parameter is + ignored). + + description (str): + A string representing the text that will be displayed in the + description field in the task scheduler. + + enabled (bool): + A boolean value representing whether or not the task is enabled. + + hidden (bool): + A boolean value representing whether or not the task is hidden. + + run_if_idle (bool): + Boolean value that indicates that the Task Scheduler will run the + task only if the computer is in an idle state. + + idle_duration (str): + A value that indicates the amount of time that the computer must be + in an idle state before the task is run. Valid values are: + + - 1 minute + - 5 minutes + - 10 minutes + - 15 minutes + - 30 minutes + - 1 hour + + idle_wait_timeout (str): + A value that indicates the amount of time that the Task Scheduler + will wait for an idle condition to occur. Valid values are: + + - Do not wait + - 1 minute + - 5 minutes + - 10 minutes + - 15 minutes + - 30 minutes + - 1 hour + - 2 hours + + idle_stop_on_end (bool): + Boolean value that indicates that the Task Scheduler will terminate + the task if the idle condition ends before the task is completed. + + idle_restart (bool): + Boolean value that indicates whether the task is restarted when the + computer cycles into an idle condition more than once. + + ac_only (bool): + Boolean value that indicates that the Task Scheduler will launch the + task only while on AC power. + + stop_if_on_batteries (bool): + Boolean value that indicates that the task will be stopped if the + computer begins to run on battery power. + + wake_to_run (bool): + Boolean value that indicates that the Task Scheduler will wake the + computer when it is time to run the task. + + run_if_network (bool): + Boolean value that indicates that the Task Scheduler will run the + task only when a network is available. + + network_id (guid): + GUID value that identifies a network profile. + + network_name (str): + Sets the name of a network profile. The name is used for display + purposes. + + allow_demand_start (bool): + Boolean value that indicates that the task can be started by using + either the Run command or the Context menu. + + start_when_available (bool): + Boolean value that indicates that the Task Scheduler can start the + task at any time after its scheduled time has passed. + + restart_every (str): + A value that specifies the interval between task restart attempts. + Valid values are: + + - False (to disable) + - 1 minute + - 5 minutes + - 10 minutes + - 15 minutes + - 30 minutes + - 1 hour + - 2 hours + + restart_count (int): + The number of times the Task Scheduler will attempt to restart the + task. Valid values are integers 1 - 999. + + execution_time_limit (bool, str): + The amount of time allowed to complete the task. Valid values are: + + - False (to disable) + - 1 hour + - 2 hours + - 4 hours + - 8 hours + - 12 hours + - 1 day + - 3 days + + force_stop (bool): + Boolean value that indicates that the task may be terminated by + using TerminateProcess. + + delete_after (bool, str): + The amount of time that the Task Scheduler will wait before deleting + the task after it expires. Requires a trigger with an expiration + date. Valid values are: + + - False (to disable) + - Immediately + - 30 days + - 90 days + - 180 days + - 365 days + + multiple_instances (str): + Sets the policy that defines how the Task Scheduler deals with + multiple instances of the task. Valid values are: + + - Parallel + - Queue + - No New Instance + - Stop Existing + + Returns: + bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash - salt 'minion-id' task.edit_task description='This task is awesome' + salt '*' task.edit_task description='This task is awesome' ''' # TODO: Add more detailed return for items changed @@ -982,7 +1051,8 @@ def edit_task(name=None, task_definition.Settings.RestartInterval = '' else: if restart_every in duration: - task_definition.Settings.RestartInterval = _lookup_first(duration, restart_every) + task_definition.Settings.RestartInterval = _lookup_first( + duration, restart_every) else: return 'Invalid value for "restart_every"' if task_definition.Settings.RestartInterval: @@ -996,7 +1066,8 @@ def edit_task(name=None, task_definition.Settings.ExecutionTimeLimit = 'PT0S' else: if execution_time_limit in duration: - task_definition.Settings.ExecutionTimeLimit = _lookup_first(duration, execution_time_limit) + task_definition.Settings.ExecutionTimeLimit = _lookup_first( + duration, execution_time_limit) else: return 'Invalid value for "execution_time_limit"' if force_stop is not None: @@ -1006,7 +1077,8 @@ def edit_task(name=None, if delete_after is False: task_definition.Settings.DeleteExpiredTaskAfter = '' if delete_after in duration: - task_definition.Settings.DeleteExpiredTaskAfter = _lookup_first(duration, delete_after) + task_definition.Settings.DeleteExpiredTaskAfter = _lookup_first( + duration, delete_after) else: return 'Invalid value for "delete_after"' if multiple_instances is not None: @@ -1027,14 +1099,17 @@ def delete_task(name, location='\\'): r''' Delete a task from the task scheduler. - :param str name: The name of the task to delete. + Args: + name (str): + The name of the task to delete. - :param str location: A string value representing the location of the task. - Default is '\\' which is the root for the task scheduler - (C:\Windows\System32\tasks). + location (str): + A string value representing the location of the task. Default is + ``\`` which is the root for the task scheduler + (``C:\Windows\System32\tasks``). - :return: True if successful, False if unsuccessful - :rtype: bool + Returns: + bool: ``True`` if successful, otherwise ``False`` CLI Example: @@ -1067,14 +1142,18 @@ def delete_folder(name, location='\\'): r''' Delete a folder from the task scheduler. - :param str name: The name of the folder to delete. + Args: - :param str location: A string value representing the location of the - folder. Default is '\\' which is the root for the task scheduler - (C:\Windows\System32\tasks). + name (str): + The name of the folder to delete. - :return: True if successful, False if unsuccessful - :rtype: bool + location (str): + A string value representing the location of the folder. Default is + ``\`` which is the root for the task scheduler + (``C:\Windows\System32\tasks``). + + Returns: + bool: ``True`` if successful, otherwise ``False`` CLI Example: @@ -1108,14 +1187,18 @@ def run(name, location='\\'): r''' Run a scheduled task manually. - :param str name: The name of the task to run. + Args: - :param str location: A string value representing the location of the task. - Default is '\\' which is the root for the task scheduler - (C:\Windows\System32\tasks). + name (str): + The name of the task to run. - :return: True if successful, False if unsuccessful - :rtype: bool + location (str): + A string value representing the location of the task. Default is + ``\`` which is the root for the task scheduler + (``C:\Windows\System32\tasks``). + + Returns: + bool: ``True`` if successful, otherwise ``False`` CLI Example: @@ -1139,7 +1222,7 @@ def run(name, location='\\'): try: task.Run('') return True - except pythoncom.com_error as error: + except pythoncom.com_error: return False @@ -1147,14 +1230,18 @@ def run_wait(name, location='\\'): r''' Run a scheduled task and return when the task finishes - :param str name: The name of the task to run. + Args: - :param str location: A string value representing the location of the task. - Default is '\\' which is the root for the task scheduler - (C:\Windows\System32\tasks). + name (str): + The name of the task to run. - :return: True if successful, False if unsuccessful - :rtype: bool + location (str): + A string value representing the location of the task. Default is + ``\`` which is the root for the task scheduler + (``C:\Windows\System32\tasks``). + + Returns: + bool: ``True`` if successful, otherwise ``False`` CLI Example: @@ -1204,14 +1291,18 @@ def stop(name, location='\\'): r''' Stop a scheduled task. - :param str name: The name of the task to stop. + Args: - :param str location: A string value representing the location of the task. - Default is '\\' which is the root for the task scheduler - (C:\Windows\System32\tasks). + name (str): + The name of the task to stop. - :return: True if successful, False if unsuccessful - :rtype: bool + location (str): + A string value representing the location of the task. Default is + ``\`` which is the root for the task scheduler + (``C:\Windows\System32\tasks``). + + Returns: + bool: ``True`` if successful, otherwise ``False`` CLI Example: @@ -1235,7 +1326,7 @@ def stop(name, location='\\'): try: task.Stop(0) return True - except pythoncom.com_error as error: + except pythoncom.com_error: return False @@ -1243,21 +1334,24 @@ def status(name, location='\\'): r''' Determine the status of a task. Is it Running, Queued, Ready, etc. - :param str name: The name of the task for which to return the status + Args: - :param str location: A string value representing the location of the task. - Default is '\\' which is the root for the task scheduler - (C:\Windows\System32\tasks). + name (str): + The name of the task for which to return the status - :return: The current status of the task. Will be one of the following: + location (str): + A string value representing the location of the task. Default is + ``\`` which is the root for the task scheduler + (``C:\Windows\System32\tasks``). - - Unknown - - Disabled - - Queued - - Ready - - Running + Returns: + str: The current status of the task. Will be one of the following: - :rtype: string + - Unknown + - Disabled + - Queued + - Ready + - Running CLI Example: @@ -1285,14 +1379,18 @@ def info(name, location='\\'): r''' Get the details about a task in the task scheduler. - :param str name: The name of the task for which to return the status + Args: - :param str location: A string value representing the location of the task. - Default is '\\' which is the root for the task scheduler - (C:\Windows\System32\tasks). + name (str): + The name of the task for which to return the status + + location (str): + A string value representing the location of the task. Default is + ``\`` which is the root for the task scheduler + (``C:\Windows\System32\tasks``). - :return: - :rtype: dict + Returns: + dict: A dictionary containing the task configuration CLI Example: @@ -1322,39 +1420,43 @@ def info(name, location='\\'): def_set = task.Definition.Settings - settings = {} - settings['allow_demand_start'] = def_set.AllowDemandStart - settings['force_stop'] = def_set.AllowHardTerminate + settings = { + 'allow_demand_start': def_set.AllowDemandStart, + 'force_stop': def_set.AllowHardTerminate} if def_set.DeleteExpiredTaskAfter == '': settings['delete_after'] = False elif def_set.DeleteExpiredTaskAfter == 'PT0S': settings['delete_after'] = 'Immediately' else: - settings['delete_after'] = _reverse_lookup(duration, def_set.DeleteExpiredTaskAfter) + settings['delete_after'] = _reverse_lookup( + duration, def_set.DeleteExpiredTaskAfter) if def_set.ExecutionTimeLimit == '': settings['execution_time_limit'] = False else: - settings['execution_time_limit'] = _reverse_lookup(duration, def_set.ExecutionTimeLimit) + settings['execution_time_limit'] = _reverse_lookup( + duration, def_set.ExecutionTimeLimit) - settings['multiple_instances'] = _reverse_lookup(instances, def_set.MultipleInstances) + settings['multiple_instances'] = _reverse_lookup( + instances, def_set.MultipleInstances) if def_set.RestartInterval == '': settings['restart_interval'] = False else: - settings['restart_interval'] = _reverse_lookup(duration, def_set.RestartInterval) + settings['restart_interval'] = _reverse_lookup( + duration, def_set.RestartInterval) if settings['restart_interval']: settings['restart_count'] = def_set.RestartCount settings['stop_if_on_batteries'] = def_set.StopIfGoingOnBatteries settings['wake_to_run'] = def_set.WakeToRun - conditions = {} - conditions['ac_only'] = def_set.DisallowStartIfOnBatteries - conditions['run_if_idle'] = def_set.RunOnlyIfIdle - conditions['run_if_network'] = def_set.RunOnlyIfNetworkAvailable - conditions['start_when_available'] = def_set.StartWhenAvailable + conditions = { + 'ac_only': def_set.DisallowStartIfOnBatteries, + 'run_if_idle': def_set.RunOnlyIfIdle, + 'run_if_network': def_set.RunOnlyIfNetworkAvailable, + 'start_when_available': def_set.StartWhenAvailable} if conditions['run_if_idle']: idle_set = def_set.IdleSettings @@ -1370,8 +1472,7 @@ def info(name, location='\\'): actions = [] for actionObj in task.Definition.Actions: - action = {} - action['action_type'] = _reverse_lookup(action_types, actionObj.Type) + action = {'action_type': _reverse_lookup(action_types, actionObj.Type)} if actionObj.Path: action['cmd'] = actionObj.Path if actionObj.Arguments: @@ -1382,10 +1483,11 @@ def info(name, location='\\'): triggers = [] for triggerObj in task.Definition.Triggers: - trigger = {} - trigger['trigger_type'] = _reverse_lookup(trigger_types, triggerObj.Type) + trigger = { + 'trigger_type': _reverse_lookup(trigger_types, triggerObj.Type)} if triggerObj.ExecutionTimeLimit: - trigger['execution_time_limit'] = _reverse_lookup(duration, triggerObj.ExecutionTimeLimit) + trigger['execution_time_limit'] = _reverse_lookup( + duration, triggerObj.ExecutionTimeLimit) if triggerObj.StartBoundary: start_date, start_time = triggerObj.StartBoundary.split('T', 1) trigger['start_date'] = start_date @@ -1397,7 +1499,8 @@ def info(name, location='\\'): trigger['enabled'] = triggerObj.Enabled if hasattr(triggerObj, 'RandomDelay'): if triggerObj.RandomDelay: - trigger['random_delay'] = _reverse_lookup(duration, triggerObj.RandomDelay) + trigger['random_delay'] = _reverse_lookup( + duration, triggerObj.RandomDelay) else: trigger['random_delay'] = False if hasattr(triggerObj, 'Delay'): @@ -1423,64 +1526,88 @@ def add_action(name=None, r''' Add an action to a task. - :param str name: The name of the task to which to add the action. + Args: - :param str location: A string value representing the location of the task. - Default is '\\' which is the root for the task scheduler - (C:\Windows\System32\tasks). + name (str): + The name of the task to which to add the action. + + location (str): + A string value representing the location of the task. Default is + ``\`` which is the root for the task scheduler + (``C:\Windows\System32\tasks``). - :param str action_type: The type of action to add. There are three action - types. Each one requires its own set of Keyword Arguments (kwargs). Valid - values are: + action_type (str): + The type of action to add. There are three action types. Each one + requires its own set of Keyword Arguments (kwargs). Valid values + are: - - Execute - - Email - - Message + - Execute + - Email + - Message Required arguments for each action_type: - **Execute** - Execute a command or an executable + **Execute** - :param str cmd: (required) The command / executable to run. + Execute a command or an executable - :param str arguments: (optional) Arguments to be passed to the command / - executable. To launch a script the first command will need to be the - interpreter for the script. For example, to run a vbscript you would - pass `cscript.exe` in the `cmd` parameter and pass the script in the - `arguments` parameter as follows: + cmd (str): + (required) The command or executable to run. - - ``cmd='cscript.exe' arguments='c:\scripts\myscript.vbs'`` + arguments (str): + (optional) Arguments to be passed to the command or executable. + To launch a script the first command will need to be the + interpreter for the script. For example, to run a vbscript you + would pass ``cscript.exe`` in the ``cmd`` parameter and pass the + script in the ``arguments`` parameter as follows: - Batch files do not need an interpreter and may be passed to the cmd - parameter directly. + - ``cmd='cscript.exe' arguments='c:\scripts\myscript.vbs'`` - :param str start_in: (optional) The current working directory for the - command. + Batch files do not need an interpreter and may be passed to the + cmd parameter directly. - **Email** - Send and email. Requires ``server``, ``from``, and ``to`` or - ``cc``. + start_in (str): + (optional) The current working directory for the command. - :param str from: The sender - :param str reply_to: Who to reply to - :param str to: The recipient - :param str cc: The CC recipient - :param str bcc: The BCC recipient - :param str subject: The subject of the email - :param str body: The Message Body of the email - :param str server: The server used to send the email - :param list attachments: A list of attachments. These will be the paths to - the files to attach. ie: ``attachments="['C:\attachment1.txt', - 'C:\attachment2.txt']"`` + **Email** - **Message** - Display a dialog box. The task must be set to "Run only when - user is logged on" in order for the dialog box to display. Both parameters - are required. + Send and email. Requires ``server``, ``from``, and ``to`` or ``cc``. - :param str title: The dialog box title. - :param str message: The dialog box message body + from (str): The sender - :return: True if successful, False if unsuccessful - :rtype: bool + reply_to (str): Who to reply to + + to (str): The recipient + + cc (str): The CC recipient + + bcc (str): The BCC recipient + + subject (str): The subject of the email + + body (str): The Message Body of the email + + server (str): The server used to send the email + + attachments (list): + A list of attachments. These will be the paths to the files to + attach. ie: ``attachments="['C:\attachment1.txt', + 'C:\attachment2.txt']"`` + + **Message** + + Display a dialog box. The task must be set to "Run only when user is + logged on" in order for the dialog box to display. Both parameters are + required. + + title (str): + The dialog box title. + + message (str): + The dialog box message body + + Returns: + dict: A dictionary containing the task configuration CLI Example: @@ -1591,8 +1718,8 @@ def _clear_actions(name, location='\\'): :param str name: The name of the task from which to clear all actions. :param str location: A string value representing the location of the task. - Default is '\\' which is the root for the task scheduler - (C:\Windows\System32\tasks). + Default is ``\`` which is the root for the task scheduler + (``C:\Windows\System32\tasks``). :return: True if successful, False if unsuccessful :rtype: bool @@ -1644,125 +1771,167 @@ def add_trigger(name=None, delay=None, **kwargs): r''' - :param str name: The name of the task to which to add the trigger. + Add a trigger to a Windows Scheduled task - :param str location: A string value representing the location of the task. - Default is '\\' which is the root for the task scheduler - (C:\Windows\System32\tasks). - - :param str trigger_type: The type of trigger to create. This is defined - when the trigger is created and cannot be changed later. Options are as - follows: - - - Event - - Once - - Daily - - Weekly - - Monthly - - MonthlyDay - - OnIdle - - OnTaskCreation - - OnBoot - - OnLogon - - OnSessionChange - - :param bool trigger_enabled: Boolean value that indicates whether the - trigger is enabled. - - :param str start_date: The date when the trigger is activated. If no value - is passed, the current date will be used. Can be one of the following - formats: - - - %Y-%m-%d - - %m-%d-%y - - %m-%d-%Y - - %m/%d/%y - - %m/%d/%Y - - %Y/%m/%d - - :param str start_time: The time when the trigger is activated. If no value - is passed, midnight will be used. Can be one of the following formats: - - - %I:%M:%S %p - - %I:%M %p - - %H:%M:%S - - %H:%M - - :param str end_date: The date when the trigger is deactivated. The trigger - cannot start the task after it is deactivated. Can be one of the - following formats: - - - %Y-%m-%d - - %m-%d-%y - - %m-%d-%Y - - %m/%d/%y - - %m/%d/%Y - - %Y/%m/%d - - :param str end_time: The time when the trigger is deactivated. If the this - is not passed with ``end_date`` it will be set to midnight. Can be one - of the following formats: - - - %I:%M:%S %p - - %I:%M %p - - %H:%M:%S - - %H:%M - - :param str random_delay: The delay time that is randomly added to the start - time of the trigger. Valid values are: - - - 30 seconds - - 1 minute - - 30 minutes - - 1 hour - - 8 hours - - 1 day - - :param str repeat_interval: The amount of time between each restart of the - task. Valid values are: - - - 5 minutes - - 10 minutes - - 15 minutes - - 30 minutes - - 1 hour - - :param str repeat_duration: How long the pattern is repeated. Valid values - are: - - - Indefinitely - - 15 minutes - - 30 minutes - - 1 hour - - 12 hours - - 1 day - - :param bool repeat_stop_at_duration_end: Boolean value that indicates if a - running instance of the task is stopped at the end of the repetition - pattern duration. - - :param str execution_time_limit: The maximum amount of time that the task - launched by the trigger is allowed to run. Valid values are: - - - 30 minutes - - 1 hour - - 2 hours - - 4 hours - - 8 hours - - 12 hours - - 1 day - - 3 days (default) - - :param str delay: The time the trigger waits after its activation to start the task. - Valid values are: - - - 15 seconds - - 30 seconds - - 1 minute - - 30 minutes - - 1 hour - - 8 hours - - 1 day + .. note:: + + Arguments are parsed by the YAML loader and are subject to + yaml's idiosyncrasies. Therefore, time values in some + formats (``%H:%M:%S`` and ``%H:%M``) should to be quoted. + See `YAML IDIOSYNCRASIES`_ for more details. + + .. _`YAML IDIOSYNCRASIES`: https://docs.saltstack.com/en/latest/topics/troubleshooting/yaml_idiosyncrasies.html#time-expressions + + Args: + + name (str): + The name of the task to which to add the trigger. + + location (str): + A string value representing the location of the task. Default is + ``\`` which is the root for the task scheduler + (``C:\Windows\System32\tasks``). + + trigger_type (str): + The type of trigger to create. This is defined when the trigger is + created and cannot be changed later. Options are as follows: + + - Event + - Once + - Daily + - Weekly + - Monthly + - MonthlyDay + - OnIdle + - OnTaskCreation + - OnBoot + - OnLogon + - OnSessionChange + + trigger_enabled (bool): + Boolean value that indicates whether the trigger is enabled. + + start_date (str): + The date when the trigger is activated. If no value is passed, the + current date will be used. Can be one of the following formats: + + - %Y-%m-%d + - %m-%d-%y + - %m-%d-%Y + - %m/%d/%y + - %m/%d/%Y + - %Y/%m/%d + + start_time (str): + The time when the trigger is activated. If no value is passed, + midnight will be used. Can be one of the following formats: + + - %I:%M:%S %p + - %I:%M %p + - %H:%M:%S + - %H:%M + + end_date (str): + The date when the trigger is deactivated. The trigger cannot start + the task after it is deactivated. Can be one of the following + formats: + + - %Y-%m-%d + - %m-%d-%y + - %m-%d-%Y + - %m/%d/%y + - %m/%d/%Y + - %Y/%m/%d + + end_time (str): + The time when the trigger is deactivated. If this is not passed + with ``end_date`` it will be set to midnight. Can be one of the + following formats: + + - %I:%M:%S %p + - %I:%M %p + - %H:%M:%S + - %H:%M + + random_delay (str): + The delay time that is randomly added to the start time of the + trigger. Valid values are: + + - 30 seconds + - 1 minute + - 30 minutes + - 1 hour + - 8 hours + - 1 day + + .. note:: + + This parameter applies to the following trigger types + + - Once + - Daily + - Weekly + - Monthly + - MonthlyDay + + repeat_interval (str): + The amount of time between each restart of the task. Valid values + are: + + - 5 minutes + - 10 minutes + - 15 minutes + - 30 minutes + - 1 hour + + repeat_duration (str): + How long the pattern is repeated. Valid values are: + + - Indefinitely + - 15 minutes + - 30 minutes + - 1 hour + - 12 hours + - 1 day + + repeat_stop_at_duration_end (bool): + Boolean value that indicates if a running instance of the task is + stopped at the end of the repetition pattern duration. + + execution_time_limit (str): + The maximum amount of time that the task launched by the trigger is + allowed to run. Valid values are: + + - 30 minutes + - 1 hour + - 2 hours + - 4 hours + - 8 hours + - 12 hours + - 1 day + - 3 days (default) + + delay (str): + The time the trigger waits after its activation to start the task. + Valid values are: + + - 15 seconds + - 30 seconds + - 1 minute + - 30 minutes + - 1 hour + - 8 hours + - 1 day + + .. note:: + + This parameter applies to the following trigger types: + + - OnLogon + - OnBoot + - Event + - OnTaskCreation + - OnSessionChange **kwargs** @@ -1771,112 +1940,136 @@ def add_trigger(name=None, *Event* - :param str subscription: An event definition in xml format that fires the - trigger. The easiest way to get this would is to create an event in - windows task scheduler and then copy the xml text. + The trigger will be fired by an event. + + subscription (str): + An event definition in xml format that fires the trigger. The + easiest way to get this would is to create an event in Windows + Task Scheduler and then copy the xml text. *Once* - No special parameters required. + No special parameters required. *Daily* - :param int days_interval: The interval between days in the schedule. An - interval of 1 produces a daily schedule. An interval of 2 produces an - every-other day schedule. If no interval is specified, 1 is used. Valid - entries are 1 - 999. + The task will run daily. + + days_interval (int): + The interval between days in the schedule. An interval of 1 + produces a daily schedule. An interval of 2 produces an + every-other day schedule. If no interval is specified, 1 is + used. Valid entries are 1 - 999. *Weekly* - :param int weeks_interval: The interval between weeks in the schedule. - An interval of 1 produces a weekly schedule. An interval of 2 produces - an every-other week schedule. If no interval is specified, 1 is used. - Valid entries are 1 - 52. + The task will run weekly. + + weeks_interval (int): + The interval between weeks in the schedule. An interval of 1 + produces a weekly schedule. An interval of 2 produces an + every-other week schedule. If no interval is specified, 1 is + used. Valid entries are 1 - 52. - param list days_of_week: Sets the days of the week on which the task - runs. Should be a list. ie: ['Monday','Wednesday','Friday']. Valid - entries are the names of the days of the week. + days_of_week (list): + Sets the days of the week on which the task runs. Should be a + list. ie: ``['Monday','Wednesday','Friday']``. Valid entries are + the names of the days of the week. *Monthly* - :param list months_of_year: Sets the months of the year during which the - task runs. Should be a list. ie: ['January','July']. Valid entries are - the full names of all the months. + The task will run monthly. + + months_of_year (list): + Sets the months of the year during which the task runs. Should + be a list. ie: ``['January','July']``. Valid entries are the + full names of all the months. - :param list days_of_month: Sets the days of the month during which the - task runs. Should be a list. ie: [1, 15, 'Last']. Options are all days - of the month 1 - 31 and the word 'Last' to indicate the last day of the - month. + days_of_month (list): + Sets the days of the month during which the task runs. Should be + a list. ie: ``[1, 15, 'Last']``. Options are all days of the + month 1 - 31 and the word 'Last' to indicate the last day of the + month. - :param bool last_day_of_month: Boolean value that indicates that the - task runs on the last day of the month regardless of the actual date of - that day. + last_day_of_month (bool): + Boolean value that indicates that the task runs on the last day + of the month regardless of the actual date of that day. - You can set the task to run on the last day of the month by either - including the word 'Last' in the list of days, or setting the parameter - 'last_day_of_month` equal to True. + .. note:: + + You can set the task to run on the last day of the month by + either including the word 'Last' in the list of days, or + setting the parameter 'last_day_of_month' equal to ``True``. *MonthlyDay* - :param list months_of_year: Sets the months of the year during which the - task runs. Should be a list. ie: ['January','July']. Valid entries are - the full names of all the months. + The task will run monthly an the specified day. + + months_of_year (list): + Sets the months of the year during which the task runs. Should + be a list. ie: ``['January','July']``. Valid entries are the + full names of all the months. - :param list weeks_of_month: Sets the weeks of the month during which the - task runs. Should be a list. ie: ['First','Third']. Valid options are: + weeks_of_month (list): + Sets the weeks of the month during which the task runs. Should + be a list. ie: ``['First','Third']``. Valid options are: - - First - - Second - - Third - - Fourth + - First + - Second + - Third + - Fourth - :param bool last_week_of_month: Boolean value that indicates that the task - runs on the last week of the month. + last_week_of_month (bool): + Boolean value that indicates that the task runs on the last week + of the month. - :param list days_of_week: Sets the days of the week during which the task - runs. Should be a list. ie: ['Monday','Wednesday','Friday']. Valid - entries are the names of the days of the week. + days_of_week (list): + Sets the days of the week during which the task runs. Should be + a list. ie: ``['Monday','Wednesday','Friday']``. Valid entries + are the names of the days of the week. *OnIdle* - No special parameters required. + + No special parameters required. *OnTaskCreation* - No special parameters required. + + No special parameters required. *OnBoot* - No special parameters required. - *OnLogon* - No special parameters required. + No special parameters required. - *OnSessionChange* + *OnLogon* - :param str session_user_name: Sets the user for the Terminal Server - session. When a session state change is detected for this user, a task - is started. To detect session status change for any user, do not pass - this parameter. + No special parameters required. - :param str state_change: Sets the kind of Terminal Server session change - that would trigger a task launch. Valid options are: + *OnSessionChange* - - ConsoleConnect: When you connect to a user session (switch users) - - ConsoleDisconnect: When you disconnect a user session (switch users) - - RemoteConnect: When a user connects via Remote Desktop - - RemoteDisconnect: When a user disconnects via Remote Desktop - - SessionLock: When the workstation is locked - - SessionUnlock: When the workstation is unlocked + The task will be triggered by a session change. - .. note:: + session_user_name (str): + Sets the user for the Terminal Server session. When a session + state change is detected for this user, a task is started. To + detect session status change for any user, do not pass this + parameter. - Arguments are parsed by the YAML loader and are subject to yaml's - idiosyncrasies. Therefore, time values in some formats (``%H:%M:%S`` and - ``%H:%M``) should to be quoted. See `YAML IDIOSYNCRASIES`_ for more details. + state_change (str): + Sets the kind of Terminal Server session change that would + trigger a task launch. Valid options are: - .. _`YAML IDIOSYNCRASIES`: https://docs.saltstack.com/en/latest/topics/troubleshooting/yaml_idiosyncrasies.html#time-expressions + - ConsoleConnect: When you connect to a user session (switch + users) + - ConsoleDisconnect: When you disconnect a user session + (switch users) + - RemoteConnect: When a user connects via Remote Desktop + - RemoteDisconnect: When a user disconnects via Remote + Desktop + - SessionLock: When the workstation is locked + - SessionUnlock: When the workstation is unlocked - - :return: True if successful, False if unsuccessful - :rtype: bool + Returns: + bool: ``True`` if successful, otherwise ``False`` CLI Example: @@ -1977,7 +2170,6 @@ def add_trigger(name=None, tm_obj.strftime('%H:%M:%S')) dt_obj = None - tm_obj = None if end_date: date_format = _get_date_time_format(end_date) if date_format: @@ -2040,10 +2232,12 @@ def add_trigger(name=None, if repeat_interval: trigger.Repetition.Interval = _lookup_first(duration, repeat_interval) if repeat_duration: - trigger.Repetition.Duration = _lookup_first(duration, repeat_duration) + trigger.Repetition.Duration = _lookup_first(duration, + repeat_duration) trigger.Repetition.StopAtDurationEnd = repeat_stop_at_duration_end if execution_time_limit: - trigger.ExecutionTimeLimit = _lookup_first(duration, execution_time_limit) + trigger.ExecutionTimeLimit = _lookup_first(duration, + execution_time_limit) if end_boundary: trigger.EndBoundary = end_boundary trigger.Enabled = trigger_enabled @@ -2098,11 +2292,12 @@ def add_trigger(name=None, trigger.DaysOfMonth = bits_days trigger.RunOnLastDayOfMonth = kwargs.get('last_day_of_month', False) else: - return 'Monthly trigger requires "days_of_month" or "last_day_of_month" parameters' + return 'Monthly trigger requires "days_of_month" or "last_day_of_' \ + 'month" parameters' # Monthly Day Of Week Trigger Parameters elif trigger_types[trigger_type] == TASK_TRIGGER_MONTHLYDOW: - trigger.Id = 'Monthy_DOW_ID1' + trigger.Id = 'Monthly_DOW_ID1' if kwargs.get('months_of_year', False): bits_months = 0 for month in kwargs.get('months_of_year'): @@ -2118,9 +2313,11 @@ def add_trigger(name=None, for week in kwargs.get('weeks_of_month'): bits_weeks |= weeks[week] trigger.WeeksOfMonth = bits_weeks - trigger.RunOnLastWeekOfMonth = kwargs.get('last_week_of_month', False) + trigger.RunOnLastWeekOfMonth = kwargs.get('last_week_of_month', + False) else: - return 'Monthly DOW trigger requires "weeks_of_month" or "last_week_of_month" parameters' + return 'Monthly DOW trigger requires "weeks_of_month" or "last_' \ + 'week_of_month" parameters' if kwargs.get('days_of_week', False): bits_days = 0 @@ -2171,14 +2368,18 @@ def clear_triggers(name, location='\\'): r''' Remove all triggers from the task. - :param str name: The name of the task from which to clear all triggers. + Args: - :param str location: A string value representing the location of the task. - Default is '\\' which is the root for the task scheduler - (C:\Windows\System32\tasks). + name (str): + The name of the task from which to clear all triggers. - :return: True if successful, False if unsuccessful - :rtype: bool + location (str): + A string value representing the location of the task. Default is + ``\`` which is the root for the task scheduler + (``C:\Windows\System32\tasks``). + + Returns: + bool: ``True`` if successful, otherwise ``False`` CLI Example: