From 0de260249928d696c63d96b71d816c94ce2a1824 Mon Sep 17 00:00:00 2001 From: Pedro Algarvio Date: Fri, 14 Jul 2023 05:18:09 +0100 Subject: [PATCH] Stop using `__utils__` in a few windows related module/states/utils Signed-off-by: Pedro Algarvio --- salt/modules/chocolatey.py | 15 +- salt/modules/environ.py | 10 +- salt/modules/pip.py | 59 +++---- salt/modules/proxy.py | 31 ++-- salt/modules/reg.py | 25 ++- salt/modules/win_auditpol.py | 7 +- salt/modules/win_file.py | 114 +++++++------- salt/modules/win_lgpo.py | 24 +-- salt/modules/win_path.py | 22 +-- salt/modules/win_pkg.py | 61 ++++---- salt/modules/win_snmp.py | 41 ++--- salt/modules/win_useradd.py | 21 +-- salt/states/environ.py | 5 +- salt/states/reg.py | 68 +++----- salt/states/win_dns_client.py | 20 +-- salt/states/win_lgpo_reg.py | 7 +- salt/utils/user.py | 8 +- salt/utils/win_chcp.py | 19 +-- salt/utils/win_dacl.py | 148 +++++++----------- salt/utils/win_dotnet.py | 20 +-- salt/utils/win_functions.py | 18 +-- salt/utils/win_lgpo_auditpol.py | 43 ++--- salt/utils/win_lgpo_netsh.py | 90 +++++------ salt/utils/win_lgpo_reg.py | 12 -- salt/utils/win_network.py | 18 +-- salt/utils/win_osinfo.py | 12 -- salt/utils/win_pdh.py | 19 +-- salt/utils/win_reg.py | 63 +++----- salt/utils/win_runas.py | 12 -- salt/utils/win_service.py | 24 +-- salt/utils/win_system.py | 21 --- salt/utils/win_update.py | 24 +-- salt/utils/winapi.py | 10 -- .../modules/win_file/test_check_perms.py | 20 +-- .../functional/utils/win_dacl/test_file.py | 31 ++-- .../functional/utils/win_dacl/test_reg.py | 33 ++-- tests/pytests/unit/modules/test_win_path.py | 47 +++--- tests/pytests/unit/states/test_environ.py | 23 +-- .../pytests/unit/utils/win_lgpo/test_netsh.py | 2 +- 39 files changed, 471 insertions(+), 776 deletions(-) diff --git a/salt/modules/chocolatey.py b/salt/modules/chocolatey.py index caa7b0bae8f8..e3d3790cf778 100644 --- a/salt/modules/chocolatey.py +++ b/salt/modules/chocolatey.py @@ -14,6 +14,7 @@ import salt.utils.data import salt.utils.platform +import salt.utils.win_dotnet from salt.exceptions import ( CommandExecutionError, CommandNotFoundError, @@ -207,7 +208,7 @@ def bootstrap(force=False, source=None): except CommandExecutionError: choc_path = None if choc_path and not force: - return "Chocolatey found at {}".format(choc_path) + return f"Chocolatey found at {choc_path}" temp_dir = tempfile.gettempdir() @@ -274,7 +275,7 @@ def bootstrap(force=False, source=None): # Check that .NET v4.0+ is installed # Windows 7 / Windows Server 2008 R2 and below do not come with at least # .NET v4.0 installed - if not __utils__["dotnet.version_at_least"](version="4"): + if not salt.utils.win_dotnet.version_at_least(version="4"): # It took until .NET v4.0 for Microsoft got the hang of making # installers, this should work under any version of Windows url = "http://download.microsoft.com/download/1/B/E/1BE39E79-7E39-46A3-96FF-047F95396215/dotNetFx40_Full_setup.exe" @@ -335,7 +336,7 @@ def bootstrap(force=False, source=None): if not os.path.exists(script): raise CommandExecutionError( - "Failed to find Chocolatey installation script: {}".format(script) + f"Failed to find Chocolatey installation script: {script}" ) # Run the Chocolatey bootstrap @@ -377,7 +378,7 @@ def unbootstrap(): if os.path.exists(choco_dir): log.debug("Removing Chocolatey directory: %s", choco_dir) __salt__["file.remove"](path=choco_dir, force=True) - removed.append("Removed Directory: {}".format(choco_dir)) + removed.append(f"Removed Directory: {choco_dir}") else: known_paths = [ os.path.join(os.environ.get("ProgramData"), "Chocolatey"), @@ -387,7 +388,7 @@ def unbootstrap(): if os.path.exists(path): log.debug("Removing Chocolatey directory: %s", path) __salt__["file.remove"](path=path, force=True) - removed.append("Removed Directory: {}".format(path)) + removed.append(f"Removed Directory: {path}") # Delete all Chocolatey environment variables for env_var in __salt__["environ.items"](): @@ -399,14 +400,14 @@ def unbootstrap(): __salt__["environ.setval"]( key=env_var, val=False, false_unsets=True, permanent="HKCU" ) - removed.append("Removed Environment Var: {}".format(env_var)) + removed.append(f"Removed Environment Var: {env_var}") # Remove Chocolatey from the path: for path in __salt__["win_path.get_path"](): if "chocolatey" in path.lower(): log.debug("Removing Chocolatey path item: %s", path) __salt__["win_path.remove"](path=path, rehash=True) - removed.append("Removed Path Item: {}".format(path)) + removed.append(f"Removed Path Item: {path}") return removed diff --git a/salt/modules/environ.py b/salt/modules/environ.py index 02dea44d4345..e50b8fd7252f 100644 --- a/salt/modules/environ.py +++ b/salt/modules/environ.py @@ -7,6 +7,8 @@ import os import salt.utils.platform +import salt.utils.win_functions +import salt.utils.win_reg log = logging.getLogger(__name__) @@ -71,8 +73,8 @@ def setval(key, val, false_unsets=False, permanent=False): try: os.environ.pop(key, None) if permanent and is_windows: - __utils__["reg.delete_value"](permanent_hive, permanent_key, key) - __utils__["win_functions.broadcast_setting_change"]() + salt.utils.win_reg.delete_value(permanent_hive, permanent_key, key) + salt.utils.win_functions.broadcast_setting_change() return None except Exception as exc: # pylint: disable=broad-except log.error( @@ -88,8 +90,8 @@ def setval(key, val, false_unsets=False, permanent=False): try: os.environ[key] = val if permanent and is_windows: - __utils__["reg.set_value"](permanent_hive, permanent_key, key, val) - __utils__["win_functions.broadcast_setting_change"]() + salt.utils.win_reg.set_value(permanent_hive, permanent_key, key, val) + salt.utils.win_functions.broadcast_setting_change() return os.environ[key] except Exception as exc: # pylint: disable=broad-except log.error( diff --git a/salt/modules/pip.py b/salt/modules/pip.py index c4de0c298465..9b34e65e788b 100644 --- a/salt/modules/pip.py +++ b/salt/modules/pip.py @@ -94,6 +94,7 @@ import salt.utils.stringutils import salt.utils.url import salt.utils.versions +import salt.utils.win_dacl from salt.exceptions import CommandExecutionError, CommandNotFoundError # This needs to be named logger so we don't shadow it in pip.install @@ -136,7 +137,7 @@ def _clear_context(bin_env=None): """ contextkey = "pip.version" if bin_env is not None: - contextkey = "{}.{}".format(contextkey, bin_env) + contextkey = f"{contextkey}.{bin_env}" __context__.pop(contextkey, None) @@ -189,7 +190,7 @@ def _search_paths(*basedirs): bin_path, ) raise CommandNotFoundError( - "Could not find a pip binary in virtualenv {}".format(bin_env) + f"Could not find a pip binary in virtualenv {bin_env}" ) # bin_env is the python or pip binary @@ -201,12 +202,10 @@ def _search_paths(*basedirs): # We have been passed a pip binary, use the pip binary. return [os.path.normpath(bin_env)] - raise CommandExecutionError( - "Could not find a pip binary within {}".format(bin_env) - ) + raise CommandExecutionError(f"Could not find a pip binary within {bin_env}") else: raise CommandNotFoundError( - "Access denied to {}, could not find a pip binary".format(bin_env) + f"Access denied to {bin_env}, could not find a pip binary" ) @@ -325,7 +324,7 @@ def _process_requirements(requirements, cmd, cwd, saltenv, user): # In Windows, just being owner of a file isn't enough. You also # need permissions if salt.utils.platform.is_windows(): - __utils__["dacl.set_permissions"]( + salt.utils.win_dacl.set_permissions( obj_name=treq, principal=user, permissions="read_execute" ) @@ -412,9 +411,7 @@ def _format_env_vars(env_vars): val = str(val) ret[key] = val else: - raise CommandExecutionError( - "env_vars {} is not a dictionary".format(env_vars) - ) + raise CommandExecutionError(f"env_vars {env_vars} is not a dictionary") return ret @@ -464,7 +461,7 @@ def install( cache_dir=None, no_binary=None, disable_version_check=False, - **kwargs + **kwargs, ): """ Install packages with pip @@ -757,9 +754,9 @@ def install( if log: if os.path.isdir(log): - raise OSError("'{}' is a directory. Use --log path_to_file".format(log)) + raise OSError(f"'{log}' is a directory. Use --log path_to_file") elif not os.access(log, os.W_OK): - raise OSError("'{}' is not writeable".format(log)) + raise OSError(f"'{log}' is not writeable") cmd.extend(["--log", log]) @@ -784,9 +781,7 @@ def install( raise ValueError("Timeout cannot be a float") int(timeout) except ValueError: - raise ValueError( - "'{}' is not a valid timeout, must be an integer".format(timeout) - ) + raise ValueError(f"'{timeout}' is not a valid timeout, must be an integer") cmd.extend(["--timeout", timeout]) if find_links: @@ -797,9 +792,7 @@ def install( if not ( salt.utils.url.validate(link, VALID_PROTOS) or os.path.exists(link) ): - raise CommandExecutionError( - "'{}' is not a valid URL or path".format(link) - ) + raise CommandExecutionError(f"'{link}' is not a valid URL or path") cmd.extend(["--find-links", link]) if no_index and (index_url or extra_index_url): @@ -809,14 +802,12 @@ def install( if index_url: if not salt.utils.url.validate(index_url, VALID_PROTOS): - raise CommandExecutionError("'{}' is not a valid URL".format(index_url)) + raise CommandExecutionError(f"'{index_url}' is not a valid URL") cmd.extend(["--index-url", index_url]) if extra_index_url: if not salt.utils.url.validate(extra_index_url, VALID_PROTOS): - raise CommandExecutionError( - "'{}' is not a valid URL".format(extra_index_url) - ) + raise CommandExecutionError(f"'{extra_index_url}' is not a valid URL") cmd.extend(["--extra-index-url", extra_index_url]) if no_index: @@ -836,7 +827,7 @@ def install( cmd.append("--use-mirrors") for mirror in mirrors: if not mirror.startswith("http://"): - raise CommandExecutionError("'{}' is not a valid URL".format(mirror)) + raise CommandExecutionError(f"'{mirror}' is not a valid URL") cmd.extend(["--mirrors", mirror]) if disable_version_check: @@ -994,7 +985,7 @@ def install( # Don't allow any recursion into keyword arg definitions # Don't allow multiple definitions of a keyword if isinstance(val, (dict, list)): - raise TypeError("Too many levels in: {}".format(key)) + raise TypeError(f"Too many levels in: {key}") # This is a a normal one-to-one keyword argument cmd.extend([key, val]) # It is a positional argument, append it to the list @@ -1107,7 +1098,7 @@ def uninstall( # TODO make this check if writeable os.path.exists(log) except OSError: - raise OSError("'{}' is not writeable".format(log)) + raise OSError(f"'{log}' is not writeable") cmd.extend(["--log", log]) @@ -1132,9 +1123,7 @@ def uninstall( raise ValueError("Timeout cannot be a float") int(timeout) except ValueError: - raise ValueError( - "'{}' is not a valid timeout, must be an integer".format(timeout) - ) + raise ValueError(f"'{timeout}' is not a valid timeout, must be an integer") cmd.extend(["--timeout", timeout]) if pkgs: @@ -1336,7 +1325,7 @@ def list_(prefix=None, bin_env=None, user=None, cwd=None, env_vars=None, **kwarg user=user, cwd=cwd, env_vars=env_vars, - **kwargs + **kwargs, ) cmd = _get_pip_bin(bin_env) @@ -1394,7 +1383,7 @@ def version(bin_env=None, cwd=None, user=None): cwd = _pip_bin_env(cwd, bin_env) contextkey = "pip.version" if bin_env is not None: - contextkey = "{}.{}".format(contextkey, bin_env) + contextkey = f"{contextkey}.{bin_env}" if contextkey in __context__: return __context__[contextkey] @@ -1650,14 +1639,12 @@ def list_all_versions( if index_url: if not salt.utils.url.validate(index_url, VALID_PROTOS): - raise CommandExecutionError("'{}' is not a valid URL".format(index_url)) + raise CommandExecutionError(f"'{index_url}' is not a valid URL") cmd.extend(["--index-url", index_url]) if extra_index_url: if not salt.utils.url.validate(extra_index_url, VALID_PROTOS): - raise CommandExecutionError( - "'{}' is not a valid URL".format(extra_index_url) - ) + raise CommandExecutionError(f"'{extra_index_url}' is not a valid URL") cmd.extend(["--extra-index-url", extra_index_url]) # Is the `pip index` command available @@ -1669,7 +1656,7 @@ def list_all_versions( if salt.utils.versions.compare(ver1=pip_version, oper=">=", ver2="20.3"): cmd.append("--use-deprecated=legacy-resolver") regex = re.compile(r"\s*Could not find a version.* \(from versions: (.*)\)") - cmd.extend(["install", "{}==versions".format(pkg)]) + cmd.extend(["install", f"{pkg}==versions"]) cmd_kwargs = dict( cwd=cwd, runas=user, output_loglevel="quiet", redirect_stderr=True diff --git a/salt/modules/proxy.py b/salt/modules/proxy.py index 370bd3eab939..9da479e77b26 100644 --- a/salt/modules/proxy.py +++ b/salt/modules/proxy.py @@ -11,6 +11,7 @@ import re import salt.utils.platform +import salt.utils.win_reg log = logging.getLogger(__name__) __virtualname__ = "proxy" @@ -28,9 +29,7 @@ def __virtual__(): def _get_proxy_osx(cmd_function, network_service): ret = {} - out = __salt__["cmd.run"]( - "networksetup -{} {}".format(cmd_function, network_service) - ) + out = __salt__["cmd.run"](f"networksetup -{cmd_function} {network_service}") match = re.match("Enabled: (.*)\nServer: (.*)\nPort: (.*)\n", out) if match is not None: g = match.groups() @@ -41,12 +40,10 @@ def _get_proxy_osx(cmd_function, network_service): def _set_proxy_osx(cmd_function, server, port, user, password, network_service): - cmd = "networksetup -{} {} {} {}".format( - cmd_function, network_service, server, port - ) + cmd = f"networksetup -{cmd_function} {network_service} {server} {port}" if user is not None and password is not None: - cmd = cmd + " On {} {}".format(user, password) + cmd += f" On {user} {password}" out = __salt__["cmd.run"](cmd) @@ -59,13 +56,13 @@ def _get_proxy_windows(types=None): if types is None: types = ["http", "https", "ftp"] - servers = __utils__["reg.read_value"]( + servers = salt.utils.win_reg.read_value( hive="HKEY_CURRENT_USER", key=r"SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings", vname="ProxyServer", )["vdata"] - if servers and "=" in servers: + if servers and "=" in servers: # pylint: disable=unsupported-membership-test split = servers.split(";") for s in split: if not s: @@ -92,7 +89,7 @@ def _get_proxy_windows(types=None): # Return enabled info ret["enabled"] = ( - __utils__["reg.read_value"]( + salt.utils.win_reg.read_value( hive="HKEY_CURRENT_USER", key=r"SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings", vname="ProxyEnable", @@ -111,16 +108,16 @@ def _set_proxy_windows( server_str = "" for t in types: - server_str += "{}={}:{};".format(t, server, port) + server_str += f"{t}={server}:{port};" - __utils__["reg.set_value"]( + salt.utils.win_reg.set_value( hive="HKEY_CURRENT_USER", key=r"SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings", vname="ProxyServer", vdata=server_str, ) - __utils__["reg.set_value"]( + salt.utils.win_reg.set_value( hive="HKEY_CURRENT_USER", key=r"SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings", vname="ProxyEnable", @@ -131,7 +128,7 @@ def _set_proxy_windows( if bypass_hosts is not None: bypass_hosts_str = ";{}".format(";".join(bypass_hosts)) - __utils__["reg.set_value"]( + salt.utils.win_reg.set_value( hive="HKEY_CURRENT_USER", key=r"SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings", vname="ProxyOverride", @@ -383,7 +380,7 @@ def get_proxy_bypass(network_service="Ethernet"): """ if __grains__["os"] == "Windows": - reg_val = __utils__["reg.read_value"]( + reg_val = salt.utils.win_reg.read_value( hive="HKEY_CURRENT_USER", key=r"SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings", vname="ProxyOverride", @@ -395,9 +392,7 @@ def get_proxy_bypass(network_service="Ethernet"): return reg_val.replace("", "").split(";") - out = __salt__["cmd.run"]( - "networksetup -getproxybypassdomains {}".format(network_service) - ) + out = __salt__["cmd.run"](f"networksetup -getproxybypassdomains {network_service}") return out.split("\n") diff --git a/salt/modules/reg.py b/salt/modules/reg.py index 229998e27a9b..47f42b3237d9 100644 --- a/salt/modules/reg.py +++ b/salt/modules/reg.py @@ -64,11 +64,10 @@ :depends: - salt.utils.win_reg """ -# When production windows installer is using Python 3, Python 2 code can be removed - import logging import salt.utils.platform +import salt.utils.win_reg from salt.exceptions import CommandExecutionError log = logging.getLogger(__name__) @@ -88,7 +87,7 @@ def __virtual__(): "The module will only run on Windows systems", ) - if "reg.read_value" not in __utils__: + if not salt.utils.win_reg.HAS_WINDOWS_MODULES: return ( False, "reg execution module failed to load: The reg salt util is unavailable", @@ -119,7 +118,7 @@ def key_exists(hive, key, use_32bit_registry=False): salt '*' reg.key_exists HKLM SOFTWARE\Microsoft """ - return __utils__["reg.key_exists"]( + return salt.utils.win_reg.key_exists( hive=hive, key=key, use_32bit_registry=use_32bit_registry ) @@ -149,7 +148,7 @@ def value_exists(hive, key, vname, use_32bit_registry=False): salt '*' reg.value_exists HKLM SOFTWARE\Microsoft\Windows\CurrentVersion CommonFilesDir """ - return __utils__["reg.value_exists"]( + return salt.utils.win_reg.value_exists( hive=hive, key=key, vname=vname, use_32bit_registry=use_32bit_registry ) @@ -206,7 +205,7 @@ def list_keys(hive, key=None, use_32bit_registry=False): salt '*' reg.list_keys HKLM 'SOFTWARE' """ - return __utils__["reg.list_keys"]( + return salt.utils.win_reg.list_keys( hive=hive, key=key, use_32bit_registry=use_32bit_registry ) @@ -247,7 +246,7 @@ def list_values(hive, key=None, use_32bit_registry=False): salt '*' reg.list_values HKLM 'SYSTEM\\CurrentControlSet\\Services\\Tcpip' """ - return __utils__["reg.list_values"]( + return salt.utils.win_reg.list_values( hive=hive, key=key, use_32bit_registry=use_32bit_registry ) @@ -307,7 +306,7 @@ def read_value(hive, key, vname=None, use_32bit_registry=False): salt '*' reg.read_value HKEY_LOCAL_MACHINE 'SOFTWARE\Salt' """ - return __utils__["reg.read_value"]( + return salt.utils.win_reg.read_value( hive=hive, key=key, vname=vname, use_32bit_registry=use_32bit_registry ) @@ -431,7 +430,7 @@ def set_value( salt '*' reg.set_value HKEY_LOCAL_MACHINE 'SOFTWARE\\Salt' 'list_data' vtype=REG_MULTI_SZ vdata='["Salt", "is", "great"]' """ - return __utils__["reg.set_value"]( + return salt.utils.win_reg.set_value( hive=hive, key=key, vname=vname, @@ -479,7 +478,7 @@ def delete_key_recursive(hive, key, use_32bit_registry=False): salt '*' reg.delete_key_recursive HKLM SOFTWARE\\delete_me """ - return __utils__["reg.delete_key_recursive"]( + return salt.utils.win_reg.delete_key_recursive( hive=hive, key=key, use_32bit_registry=use_32bit_registry ) @@ -519,7 +518,7 @@ def delete_value(hive, key, vname=None, use_32bit_registry=False): salt '*' reg.delete_value HKEY_CURRENT_USER 'SOFTWARE\\Salt' 'version' """ - return __utils__["reg.delete_value"]( + return salt.utils.win_reg.delete_value( hive=hive, key=key, vname=vname, use_32bit_registry=use_32bit_registry ) @@ -558,13 +557,13 @@ def import_file(source, use_32bit_registry=False): """ cache_path = __salt__["cp.cache_file"](source) if not cache_path: - error_msg = "File/URL '{}' probably invalid.".format(source) + error_msg = f"File/URL '{source}' probably invalid." raise ValueError(error_msg) if use_32bit_registry: word_sz_txt = "32" else: word_sz_txt = "64" - cmd = 'reg import "{}" /reg:{}'.format(cache_path, word_sz_txt) + cmd = f'reg import "{cache_path}" /reg:{word_sz_txt}' cmd_ret_dict = __salt__["cmd.run_all"](cmd, python_shell=True) retcode = cmd_ret_dict["retcode"] if retcode != 0: diff --git a/salt/modules/win_auditpol.py b/salt/modules/win_auditpol.py index 29c1c535bd73..0d6ca81bc910 100644 --- a/salt/modules/win_auditpol.py +++ b/salt/modules/win_auditpol.py @@ -55,6 +55,7 @@ """ import salt.utils.platform +import salt.utils.win_lgpo_auditpol # Define the module's virtual name __virtualname__ = "auditpol" @@ -112,7 +113,7 @@ def get_settings(category="All"): # category salt * auditpol.get_settings "Account Logon" """ - return __utils__["auditpol.get_settings"](category=category) + return salt.utils.win_lgpo_auditpol.get_settings(category=category) def get_setting(name): @@ -136,7 +137,7 @@ def get_setting(name): # Get current state of the "Credential Validation" setting salt * auditpol.get_setting "Credential Validation" """ - return __utils__["auditpol.get_setting"](name=name) + return salt.utils.win_lgpo_auditpol.get_setting(name=name) def set_setting(name, value): @@ -174,4 +175,4 @@ def set_setting(name, value): # Set the state of the "Credential Validation" setting to No Auditing salt * auditpol.set_setting "Credential Validation" "No Auditing" """ - return __utils__["auditpol.set_setting"](name=name, value=value) + return salt.utils.win_lgpo_auditpol.set_setting(name=name, value=value) diff --git a/salt/modules/win_file.py b/salt/modules/win_file.py index d02d4589f2fa..1e6744912b51 100644 --- a/salt/modules/win_file.py +++ b/salt/modules/win_file.py @@ -16,8 +16,11 @@ import sys import tempfile +import salt.utils.files import salt.utils.path import salt.utils.platform +import salt.utils.user +import salt.utils.win_dacl from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.modules.file import ( __clean_tmp, @@ -259,7 +262,7 @@ def gid_to_group(gid): salt '*' file.gid_to_group S-1-5-21-626487655-2533044672-482107328-1010 """ - func_name = "{}.gid_to_group".format(__virtualname__) + func_name = f"{__virtualname__}.gid_to_group" if __opts__.get("fun", "") == func_name: log.info( "The function %s should not be used on Windows systems; " @@ -294,7 +297,7 @@ def group_to_gid(group): salt '*' file.group_to_gid administrators """ - func_name = "{}.group_to_gid".format(__virtualname__) + func_name = f"{__virtualname__}.group_to_gid" if __opts__.get("fun", "") == func_name: log.info( "The function %s should not be used on Windows systems; " @@ -305,7 +308,7 @@ def group_to_gid(group): if group is None: return "" - return __utils__["dacl.get_sid_string"](group) + return salt.utils.win_dacl.get_sid_string(group) def get_pgid(path, follow_symlinks=True): @@ -336,7 +339,7 @@ def get_pgid(path, follow_symlinks=True): salt '*' file.get_pgid c:\\temp\\test.txt """ if not os.path.exists(path): - raise CommandExecutionError("Path not found: {}".format(path)) + raise CommandExecutionError(f"Path not found: {path}") # Under Windows, if the path is a symlink, the user that owns the symlink is # returned, not the user that owns the file/directory the symlink is @@ -346,8 +349,8 @@ def get_pgid(path, follow_symlinks=True): if follow_symlinks and sys.getwindowsversion().major >= 6: path = _resolve_symlink(path) - group_name = __utils__["dacl.get_primary_group"](path) - return __utils__["dacl.get_sid_string"](group_name) + group_name = salt.utils.win_dacl.get_primary_group(path) + return salt.utils.win_dacl.get_sid_string(group_name) def get_pgroup(path, follow_symlinks=True): @@ -420,7 +423,7 @@ def get_gid(path, follow_symlinks=True): salt '*' file.get_gid c:\\temp\\test.txt """ - func_name = "{}.get_gid".format(__virtualname__) + func_name = f"{__virtualname__}.get_gid" if __opts__.get("fun", "") == func_name: log.info( "The function %s should not be used on Windows systems; " @@ -467,7 +470,7 @@ def get_group(path, follow_symlinks=True): salt '*' file.get_group c:\\temp\\test.txt """ - func_name = "{}.get_group".format(__virtualname__) + func_name = f"{__virtualname__}.get_group" if __opts__.get("fun", "") == func_name: log.info( "The function %s should not be used on Windows systems; " @@ -498,7 +501,7 @@ def uid_to_user(uid): if uid is None or uid == "": return "" - return __utils__["dacl.get_name"](uid) + return salt.utils.win_dacl.get_name(uid) def user_to_uid(user): @@ -518,9 +521,9 @@ def user_to_uid(user): salt '*' file.user_to_uid myusername """ if user is None: - user = __utils__["user.get_user"]() + user = salt.utils.win_user.get_user() - return __utils__["dacl.get_sid_string"](user) + return salt.utils.win_dacl.get_sid_string(user) def get_uid(path, follow_symlinks=True): @@ -548,7 +551,7 @@ def get_uid(path, follow_symlinks=True): salt '*' file.get_uid c:\\temp\\test.txt follow_symlinks=False """ if not os.path.exists(path): - raise CommandExecutionError("Path not found: {}".format(path)) + raise CommandExecutionError(f"Path not found: {path}") # Under Windows, if the path is a symlink, the user that owns the symlink is # returned, not the user that owns the file/directory the symlink is @@ -558,8 +561,8 @@ def get_uid(path, follow_symlinks=True): if follow_symlinks and sys.getwindowsversion().major >= 6: path = _resolve_symlink(path) - owner_sid = __utils__["dacl.get_owner"](path) - return __utils__["dacl.get_sid_string"](owner_sid) + owner_sid = salt.utils.win_dacl.get_owner(path) + return salt.utils.win_dacl.get_sid_string(owner_sid) def get_user(path, follow_symlinks=True): @@ -587,7 +590,7 @@ def get_user(path, follow_symlinks=True): salt '*' file.get_user c:\\temp\\test.txt follow_symlinks=False """ if not os.path.exists(path): - raise CommandExecutionError("Path not found: {}".format(path)) + raise CommandExecutionError(f"Path not found: {path}") # Under Windows, if the path is a symlink, the user that owns the symlink is # returned, not the user that owns the file/directory the symlink is @@ -597,7 +600,7 @@ def get_user(path, follow_symlinks=True): if follow_symlinks and sys.getwindowsversion().major >= 6: path = _resolve_symlink(path) - return __utils__["dacl.get_owner"](path) + return salt.utils.win_dacl.get_owner(path) def get_mode(path): @@ -620,9 +623,9 @@ def get_mode(path): salt '*' file.get_mode /etc/passwd """ if not os.path.exists(path): - raise CommandExecutionError("Path not found: {}".format(path)) + raise CommandExecutionError(f"Path not found: {path}") - func_name = "{}.get_mode".format(__virtualname__) + func_name = f"{__virtualname__}.get_mode" if __opts__.get("fun", "") == func_name: log.info( "The function %s should not be used on Windows systems; " @@ -671,7 +674,7 @@ def lchown(path, user, group=None, pgroup=None): salt '*' file.lchown c:\\temp\\test.txt myusername "pgroup='None'" """ if group: - func_name = "{}.lchown".format(__virtualname__) + func_name = f"{__virtualname__}.lchown" if __opts__.get("fun", "") == func_name: log.info( "The group parameter has no effect when using %s on " @@ -720,7 +723,7 @@ def chown(path, user, group=None, pgroup=None, follow_symlinks=True): """ # the group parameter is not used; only provided for API compatibility if group is not None: - func_name = "{}.chown".format(__virtualname__) + func_name = f"{__virtualname__}.chown" if __opts__.get("fun", "") == func_name: log.info( "The group parameter has no effect when using %s on " @@ -733,11 +736,11 @@ def chown(path, user, group=None, pgroup=None, follow_symlinks=True): path = _resolve_symlink(path) if not os.path.exists(path): - raise CommandExecutionError("Path not found: {}".format(path)) + raise CommandExecutionError(f"Path not found: {path}") - __utils__["dacl.set_owner"](path, user) + salt.utils.win_dacl.set_owner(path, user) if pgroup: - __utils__["dacl.set_primary_group"](path, pgroup) + salt.utils.win_dacl.set_primary_group(path, pgroup) return True @@ -767,7 +770,7 @@ def chpgrp(path, group): salt '*' file.chpgrp c:\\temp\\test.txt Administrators salt '*' file.chpgrp c:\\temp\\test.txt "'None'" """ - return __utils__["dacl.set_primary_group"](path, group) + return salt.utils.win_dacl.set_primary_group(path, group) def chgrp(path, group): @@ -804,7 +807,7 @@ def chgrp(path, group): salt '*' file.chpgrp c:\\temp\\test.txt administrators """ - func_name = "{}.chgrp".format(__virtualname__) + func_name = f"{__virtualname__}.chgrp" if __opts__.get("fun", "") == func_name: log.info( "The function %s should not be used on Windows systems; see " @@ -850,7 +853,7 @@ def stats(path, hash_type="sha256", follow_symlinks=True): # This is to mirror the behavior of file.py. `check_file_meta` expects an # empty dictionary when the file does not exist if not os.path.exists(path): - raise CommandExecutionError("Path not found: {}".format(path)) + raise CommandExecutionError(f"Path not found: {path}") if follow_symlinks and sys.getwindowsversion().major >= 6: path = _resolve_symlink(path) @@ -871,7 +874,7 @@ def stats(path, hash_type="sha256", follow_symlinks=True): ret["mtime"] = pstat.st_mtime ret["ctime"] = pstat.st_ctime ret["size"] = pstat.st_size - ret["mode"] = __utils__["files.normalize_mode"](oct(stat.S_IMODE(pstat.st_mode))) + ret["mode"] = salt.utils.files.normalize_mode(oct(stat.S_IMODE(pstat.st_mode))) if hash_type: ret["sum"] = get_sum(path, hash_type) ret["type"] = "file" @@ -953,13 +956,13 @@ def _get_version_type(file_type, file_subtype): if ret_type == "Driver": if file_subtype in driver_subtypes: - ret_type = "{} Driver".format(driver_subtypes[file_subtype]) + ret_type = f"{driver_subtypes[file_subtype]} Driver" if ret_type == "Font": if file_subtype in font_subtypes: - ret_type = "{} Font".format(font_subtypes[file_subtype]) + ret_type = f"{font_subtypes[file_subtype]} Font" if ret_type == "Virtual Device": # The Virtual Device Identifier - ret_type = "Virtual Device: {}".format(file_subtype) + ret_type = f"Virtual Device: {file_subtype}" return ret_type @@ -1028,9 +1031,9 @@ def version(path): """ # Input validation if not os.path.exists(path): - raise CommandExecutionError("File not found: {}".format(path)) + raise CommandExecutionError(f"File not found: {path}") if os.path.isdir(path): - raise CommandExecutionError("Not a file: {}".format(path)) + raise CommandExecutionError(f"Not a file: {path}") return _get_version(path) @@ -1068,9 +1071,9 @@ def version_details(path): """ # Input validation if not os.path.exists(path): - raise CommandExecutionError("File not found: {}".format(path)) + raise CommandExecutionError(f"File not found: {path}") if os.path.isdir(path): - raise CommandExecutionError("Not a file: {}".format(path)) + raise CommandExecutionError(f"Not a file: {path}") ret = {} try: @@ -1146,7 +1149,7 @@ def get_attributes(path): salt '*' file.get_attributes c:\\temp\\a.txt """ if not os.path.exists(path): - raise CommandExecutionError("Path not found: {}".format(path)) + raise CommandExecutionError(f"Path not found: {path}") # set up dictionary for attribute values attributes = {} @@ -1228,7 +1231,7 @@ def set_attributes( salt '*' file.set_attributes c:\\temp\\a.txt readonly=True hidden=True """ if not os.path.exists(path): - raise CommandExecutionError("Path not found: {}".format(path)) + raise CommandExecutionError(f"Path not found: {path}") if normal: if archive or hidden or notIndexed or readonly or system or temporary: @@ -1297,7 +1300,7 @@ def set_mode(path, mode): salt '*' file.set_mode /etc/passwd 0644 """ - func_name = "{}.set_mode".format(__virtualname__) + func_name = f"{__virtualname__}.set_mode" if __opts__.get("fun", "") == func_name: log.info( "The function %s should not be used on Windows systems; " @@ -1333,11 +1336,11 @@ def remove(path, force=False): path = os.path.expanduser(path) if not os.path.isabs(path): - raise SaltInvocationError("File path must be absolute: {}".format(path)) + raise SaltInvocationError(f"File path must be absolute: {path}") # Does the file/folder exists if not os.path.exists(path) and not is_link(path): - raise CommandExecutionError("Path not found: {}".format(path)) + raise CommandExecutionError(f"Path not found: {path}") # Remove ReadOnly Attribute if force: @@ -1354,7 +1357,7 @@ def remove(path, force=False): os.rmdir(path) else: for name in os.listdir(path): - item = "{}\\{}".format(path, name) + item = f"{path}\\{name}" # If its a normal directory, recurse to remove it's contents remove(item, force) @@ -1364,7 +1367,7 @@ def remove(path, force=False): if force: # Reset attributes to the original if delete fails. win32api.SetFileAttributes(path, file_attributes) - raise CommandExecutionError("Could not remove '{}': {}".format(path, exc)) + raise CommandExecutionError(f"Could not remove '{path}': {exc}") return True @@ -1412,7 +1415,7 @@ def symlink(src, link, force=False, atomic=False): ) if not os.path.isabs(link): - raise SaltInvocationError("Link path must be absolute: {}".format(link)) + raise SaltInvocationError(f"Link path must be absolute: {link}") if os.path.islink(link): try: @@ -1425,11 +1428,11 @@ def symlink(src, link, force=False, atomic=False): pass if not force and not atomic: - msg = "Found existing symlink: {}".format(link) + msg = f"Found existing symlink: {link}" raise CommandExecutionError(msg) if os.path.exists(link) and not force and not atomic: - msg = "Existing path is not a symlink: {}".format(link) + msg = f"Existing path is not a symlink: {link}" raise CommandExecutionError(msg) # ensure paths are using the right slashes @@ -1464,14 +1467,14 @@ def symlink(src, link, force=False, atomic=False): return True except win32file.error: os.remove(temp_link) - raise CommandExecutionError("Could not create '{}'".format(link)) + raise CommandExecutionError(f"Could not create '{link}'") try: win32file.CreateSymbolicLink(link, src, int(is_dir)) return True except win32file.error as exc: raise CommandExecutionError( - "Could not create '{}' - [{}] {}".format(link, exc.winerror, exc.strerror) + f"Could not create '{link}' - [{exc.winerror}] {exc.strerror}" ) @@ -1503,7 +1506,7 @@ def is_link(path): ) try: - return __utils__["path.islink"](path) + return salt.utils.path.islink(path) except Exception as exc: # pylint: disable=broad-except raise CommandExecutionError(exc) @@ -1581,7 +1584,7 @@ def mkdir( # Make sure the drive is valid drive = os.path.splitdrive(path)[0] if not os.path.isdir(drive): - raise CommandExecutionError("Drive {} is not mapped".format(drive)) + raise CommandExecutionError(f"Drive {drive} is not mapped") path = os.path.expanduser(path) path = os.path.expandvars(path) @@ -1594,10 +1597,10 @@ def mkdir( # Set owner if owner: - __utils__["dacl.set_owner"](obj_name=path, principal=owner) + salt.utils.win_dacl.set_owner(obj_name=path, principal=owner) # Set permissions - __utils__["dacl.set_perms"]( + salt.utils.win_dacl.set_perms( obj_name=path, obj_type="file", grant_perms=grant_perms, @@ -1698,12 +1701,12 @@ def makedirs_( if os.path.isdir(dirname): # There's nothing for us to do - msg = "Directory '{}' already exists".format(dirname) + msg = f"Directory '{dirname}' already exists" log.debug(msg) return msg if os.path.exists(dirname): - msg = "The path '{}' already exists and is not a directory".format(dirname) + msg = f"The path '{dirname}' already exists and is not a directory" log.debug(msg) return msg @@ -1912,11 +1915,11 @@ def check_perms( salt '*' file.check_perms C:\\Temp\\ {} Administrators "{'jsnuffy': {'perms': ['read_attributes', 'read_ea'], 'applies_to': 'files_only'}}" """ if not os.path.exists(path): - raise CommandExecutionError("Path not found: {}".format(path)) + raise CommandExecutionError(f"Path not found: {path}") path = os.path.expanduser(path) - return __utils__["dacl.check_perms"]( + return salt.utils.win_dacl.check_perms( obj_name=path, obj_type="file", ret=ret, @@ -1925,6 +1928,7 @@ def check_perms( deny_perms=deny_perms, inheritance=inheritance, reset=reset, + test_mode=__opts__.get("test", False), ) @@ -2002,7 +2006,7 @@ def set_perms(path, grant_perms=None, deny_perms=None, inheritance=True, reset=F # Specify advanced attributes with a list salt '*' file.set_perms C:\\Temp\\ "{'jsnuffy': {'perms': ['read_attributes', 'read_ea'], 'applies_to': 'this_folder_only'}}" """ - return __utils__["dacl.set_perms"]( + return salt.utils.win_dacl.set_perms( obj_name=path, obj_type="file", grant_perms=grant_perms, diff --git a/salt/modules/win_lgpo.py b/salt/modules/win_lgpo.py index 4151a383f4c8..4dca07a35e57 100644 --- a/salt/modules/win_lgpo.py +++ b/salt/modules/win_lgpo.py @@ -59,7 +59,9 @@ import salt.utils.path import salt.utils.platform import salt.utils.stringutils +import salt.utils.win_lgpo_auditpol import salt.utils.win_lgpo_netsh +import salt.utils.win_reg from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.serializers.configparser import deserialize from salt.utils.win_lgpo_reg import ( @@ -76,7 +78,7 @@ __func_alias__ = {"set_": "set"} UUID = uuid.uuid4().hex -adm_policy_name_map = {True: {}, False: {}} +ADM_POLICY_NAME_MAP = {True: {}, False: {}} HAS_WINDOWS_MODULES = False # define some global XPATH variables that we'll set assuming all our imports are # good @@ -5392,7 +5394,7 @@ def _get_advaudit_defaults(option=None): # Get available setting names and GUIDs # This is used to get the fieldnames and GUIDs for individual policies log.debug("Loading auditpol defaults into __context__") - dump = __utils__["auditpol.get_auditpol_dump"]() + dump = salt.utils.win_lgpo_auditpol.get_auditpol_dump() reader = csv.DictReader(dump) audit_defaults = {"fieldnames": reader.fieldnames} for row in reader: @@ -5624,7 +5626,7 @@ def _set_advaudit_pol_data(option, value): "3": "Success and Failure", } defaults = _get_advaudit_defaults(option) - return __utils__["auditpol.set_setting"]( + return salt.utils.win_lgpo_auditpol.set_setting( name=defaults["Auditpol Name"], value=auditpol_values[value] ) @@ -6007,20 +6009,20 @@ def _getFullPolicyName( """ helper function to retrieve the full policy name if needed """ - if policy_name in adm_policy_name_map[return_full_policy_names]: - return adm_policy_name_map[return_full_policy_names][policy_name] + if policy_name in ADM_POLICY_NAME_MAP[return_full_policy_names]: + return ADM_POLICY_NAME_MAP[return_full_policy_names][policy_name] adml_data = _get_policy_resources(language=adml_language) if return_full_policy_names and "displayName" in policy_item.attrib: fullPolicyName = _getAdmlDisplayName( adml_data, policy_item.attrib["displayName"] ) if fullPolicyName: - adm_policy_name_map[return_full_policy_names][policy_name] = fullPolicyName + ADM_POLICY_NAME_MAP[return_full_policy_names][policy_name] = fullPolicyName policy_name = fullPolicyName elif return_full_policy_names and "id" in policy_item.attrib: fullPolicyName = _getAdmlPresentationRefId(adml_data, policy_item.attrib["id"]) if fullPolicyName: - adm_policy_name_map[return_full_policy_names][policy_name] = fullPolicyName + ADM_POLICY_NAME_MAP[return_full_policy_names][policy_name] = fullPolicyName policy_name = fullPolicyName policy_name = policy_name.rstrip(":").rstrip() return policy_name @@ -8903,7 +8905,7 @@ def _get_policy_info_setting(policy_definition): """ if "Registry" in policy_definition: # Get value using the Registry mechanism - value = __utils__["reg.read_value"]( + value = salt.utils.win_reg.read_value( policy_definition["Registry"]["Hive"], policy_definition["Registry"]["Path"], policy_definition["Registry"]["Value"], @@ -10348,7 +10350,7 @@ class in this module. _regedits[regedit]["value"] is not None and _regedits[regedit]["value"] != "(value not set)" ): - _ret = __utils__["reg.set_value"]( + _ret = salt.utils.win_reg.set_value( _regedits[regedit]["policy"]["Registry"]["Hive"], _regedits[regedit]["policy"]["Registry"]["Path"], _regedits[regedit]["policy"]["Registry"]["Value"], @@ -10356,13 +10358,13 @@ class in this module. _regedits[regedit]["policy"]["Registry"]["Type"], ) else: - _ret = __utils__["reg.read_value"]( + _ret = salt.utils.win_reg.read_value( _regedits[regedit]["policy"]["Registry"]["Hive"], _regedits[regedit]["policy"]["Registry"]["Path"], _regedits[regedit]["policy"]["Registry"]["Value"], ) if _ret["success"] and _ret["vdata"] != "(value not set)": - _ret = __utils__["reg.delete_value"]( + _ret = salt.utils.win_reg.delete_value( _regedits[regedit]["policy"]["Registry"]["Hive"], _regedits[regedit]["policy"]["Registry"]["Path"], _regedits[regedit]["policy"]["Registry"]["Value"], diff --git a/salt/modules/win_path.py b/salt/modules/win_path.py index e6da271cb489..0e2fe6a90562 100644 --- a/salt/modules/win_path.py +++ b/salt/modules/win_path.py @@ -13,27 +13,21 @@ import salt.utils.platform import salt.utils.stringutils import salt.utils.win_functions +import salt.utils.win_reg -try: - HAS_WIN32 = True -except ImportError: - HAS_WIN32 = False - -# Settings log = logging.getLogger(__name__) HIVE = "HKEY_LOCAL_MACHINE" KEY = "SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment" VNAME = "PATH" VTYPE = "REG_EXPAND_SZ" -PATHSEP = str(os.pathsep) def __virtual__(): """ Load only on Windows """ - if salt.utils.platform.is_windows() and HAS_WIN32: + if salt.utils.platform.is_windows(): return "win_path" return (False, "Module win_path: module only works on Windows systems") @@ -77,7 +71,7 @@ def get_path(): salt '*' win_path.get_path """ ret = salt.utils.stringutils.to_unicode( - __utils__["reg.read_value"]( + salt.utils.win_reg.read_value( "HKEY_LOCAL_MACHINE", "SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment", "PATH", @@ -114,7 +108,7 @@ def exists(path): def _update_local_path(local_path): - os.environ["PATH"] = PATHSEP.join(local_path) + os.environ["PATH"] = os.pathsep.join(local_path) def add(path, index=None, **kwargs): @@ -159,7 +153,7 @@ def add(path, index=None, **kwargs): # The current path should not have any unicode in it, but don't take any # chances. local_path = [ - salt.utils.stringutils.to_str(x) for x in os.environ["PATH"].split(PATHSEP) + salt.utils.stringutils.to_str(x) for x in os.environ["PATH"].split(os.pathsep) ] if index is not None: @@ -270,7 +264,7 @@ def _check_path(dirs, path, index): return True # Move forward with registry update - result = __utils__["reg.set_value"]( + result = salt.utils.win_reg.set_value( HIVE, KEY, VNAME, ";".join(salt.utils.data.decode(system_path)), VTYPE ) @@ -312,7 +306,7 @@ def remove(path, **kwargs): # The current path should not have any unicode in it, but don't take any # chances. local_path = [ - salt.utils.stringutils.to_str(x) for x in os.environ["PATH"].split(PATHSEP) + salt.utils.stringutils.to_str(x) for x in os.environ["PATH"].split(os.pathsep) ] def _check_path(dirs, path): @@ -341,7 +335,7 @@ def _check_path(dirs, path): # No changes necessary return True - result = __utils__["reg.set_value"]( + result = salt.utils.win_reg.set_value( HIVE, KEY, VNAME, ";".join(salt.utils.data.decode(system_path)), VTYPE ) diff --git a/salt/modules/win_pkg.py b/salt/modules/win_pkg.py index c2ea64d823a7..709cf5224dd8 100644 --- a/salt/modules/win_pkg.py +++ b/salt/modules/win_pkg.py @@ -59,6 +59,7 @@ import salt.utils.platform import salt.utils.versions import salt.utils.win_functions +import salt.utils.win_reg from salt.exceptions import ( CommandExecutionError, MinionError, @@ -488,14 +489,14 @@ def skip_component(hive, key, sub_key, use_32bit_registry): """ if include_components: return False - if __utils__["reg.value_exists"]( + if salt.utils.win_reg.value_exists( hive=hive, key=f"{key}\\{sub_key}", vname="SystemComponent", use_32bit_registry=use_32bit_registry, ): if ( - __utils__["reg.read_value"]( + salt.utils.win_reg.read_value( hive=hive, key=f"{key}\\{sub_key}", vname="SystemComponent", @@ -517,14 +518,14 @@ def skip_win_installer(hive, key, sub_key, use_32bit_registry): bool: True if the package needs to be skipped, otherwise False """ products_key = "Software\\Classes\\Installer\\Products\\{0}" - if __utils__["reg.value_exists"]( + if salt.utils.win_reg.value_exists( hive=hive, key=f"{key}\\{sub_key}", vname="WindowsInstaller", use_32bit_registry=use_32bit_registry, ): if ( - __utils__["reg.read_value"]( + salt.utils.win_reg.read_value( hive=hive, key=f"{key}\\{sub_key}", vname="WindowsInstaller", @@ -533,7 +534,7 @@ def skip_win_installer(hive, key, sub_key, use_32bit_registry): > 0 ): squid = salt.utils.win_functions.guid_to_squid(sub_key) - if not __utils__["reg.key_exists"]( + if not salt.utils.win_reg.key_exists( hive="HKLM", key=products_key.format(squid), use_32bit_registry=use_32bit_registry, @@ -555,14 +556,14 @@ def skip_uninstall_string(hive, key, sub_key, use_32bit_registry): bool: True if the package needs to be skipped, otherwise False """ # https://docs.microsoft.com/en-us/windows/win32/msi/arpnoremove - if __utils__["reg.value_exists"]( + if salt.utils.win_reg.value_exists( hive=hive, key=f"{key}\\{sub_key}", vname="NoRemove", use_32bit_registry=use_32bit_registry, ): if ( - __utils__["reg.read_value"]( + salt.utils.win_reg.read_value( hive=hive, key=f"{key}\\{sub_key}", vname="NoRemove", @@ -571,7 +572,7 @@ def skip_uninstall_string(hive, key, sub_key, use_32bit_registry): > 0 ): return False - if not __utils__["reg.value_exists"]( + if not salt.utils.win_reg.value_exists( hive=hive, key=f"{key}\\{sub_key}", vname="UninstallString", @@ -592,14 +593,14 @@ def skip_release_type(hive, key, sub_key, use_32bit_registry): if include_updates: return False skip_types = ["Hotfix", "Security Update", "Update Rollup"] - if __utils__["reg.value_exists"]( + if salt.utils.win_reg.value_exists( hive=hive, key=f"{key}\\{sub_key}", vname="ReleaseType", use_32bit_registry=use_32bit_registry, ): if ( - __utils__["reg.read_value"]( + salt.utils.win_reg.read_value( hive=hive, key=f"{key}\\{sub_key}", vname="ReleaseType", @@ -618,7 +619,7 @@ def skip_parent_key(hive, key, sub_key, use_32bit_registry): Returns: bool: True if the package needs to be skipped, otherwise False """ - if __utils__["reg.value_exists"]( + if salt.utils.win_reg.value_exists( hive=hive, key=f"{key}\\{sub_key}", vname="ParentKeyName", @@ -635,7 +636,7 @@ def add_software(hive, key, sub_key, use_32bit_registry): not start with 'KB' followed by 6 numbers - as that indicates a Windows update. """ - d_name_regdata = __utils__["reg.read_value"]( + d_name_regdata = salt.utils.win_reg.read_value( hive=hive, key=f"{key}\\{sub_key}", vname="DisplayName", @@ -654,7 +655,7 @@ def add_software(hive, key, sub_key, use_32bit_registry): if re.match(r"^KB[0-9]{6}", d_name): return - d_vers_regdata = __utils__["reg.read_value"]( + d_vers_regdata = salt.utils.win_reg.read_value( hive=hive, key=f"{key}\\{sub_key}", vname="DisplayVersion", @@ -683,7 +684,7 @@ def add_software(hive, key, sub_key, use_32bit_registry): "key": "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall", "use_32bit_registry": False, } - for sub_key in __utils__["reg.list_keys"](**kwargs): + for sub_key in salt.utils.win_reg.list_keys(**kwargs): kwargs["sub_key"] = sub_key if skip_component(**kwargs): continue @@ -700,7 +701,7 @@ def add_software(hive, key, sub_key, use_32bit_registry): # HKLM Uninstall 32 bit kwargs["use_32bit_registry"] = True kwargs.pop("sub_key", False) - for sub_key in __utils__["reg.list_keys"](**kwargs): + for sub_key in salt.utils.win_reg.list_keys(**kwargs): kwargs["sub_key"] = sub_key if skip_component(**kwargs): continue @@ -724,9 +725,9 @@ def add_software(hive, key, sub_key, use_32bit_registry): "Software\\Microsoft\\Windows\\CurrentVersion\\Installer\\" "UserData\\S-1-5-18\\Products" ) - for sub_key in __utils__["reg.list_keys"](**kwargs): + for sub_key in salt.utils.win_reg.list_keys(**kwargs): # If the key does not exist in userdata, skip it - if not __utils__["reg.key_exists"]( + if not salt.utils.win_reg.key_exists( hive=kwargs["hive"], key=f"{userdata_key}\\{sub_key}" ): continue @@ -747,14 +748,14 @@ def add_software(hive, key, sub_key, use_32bit_registry): "Software\\Microsoft\\Windows\\CurrentVersion\\Installer\\" "UserData\\{0}\\Products\\{1}" ) - for user_guid in __utils__["reg.list_keys"](hive=hive_hku): + for user_guid in salt.utils.win_reg.list_keys(hive=hive_hku): kwargs = { "hive": hive_hku, "key": uninstall_key.format(user_guid), "use_32bit_registry": False, } - if __utils__["reg.key_exists"](**kwargs): - for sub_key in __utils__["reg.list_keys"](**kwargs): + if salt.utils.win_reg.key_exists(**kwargs): + for sub_key in salt.utils.win_reg.list_keys(**kwargs): kwargs["sub_key"] = sub_key if skip_component(**kwargs): continue @@ -774,28 +775,30 @@ def add_software(hive, key, sub_key, use_32bit_registry): "key": product_key.format(user_guid), "use_32bit_registry": False, } - if __utils__["reg.key_exists"](**kwargs): - for sub_key in __utils__["reg.list_keys"](**kwargs): + if salt.utils.win_reg.key_exists(**kwargs): + for sub_key in salt.utils.win_reg.list_keys(**kwargs): kwargs = { "hive": "HKLM", "key": user_data_key.format(user_guid, sub_key), "use_32bit_registry": False, } - if __utils__["reg.key_exists"](**kwargs): + if salt.utils.win_reg.key_exists(**kwargs): kwargs["sub_key"] = "InstallProperties" if skip_component(**kwargs): continue add_software(**kwargs) # Uninstall for each user on the system (HKU), 32 bit - for user_guid in __utils__["reg.list_keys"](hive=hive_hku, use_32bit_registry=True): + for user_guid in salt.utils.win_reg.list_keys( + hive=hive_hku, use_32bit_registry=True + ): kwargs = { "hive": hive_hku, "key": uninstall_key.format(user_guid), "use_32bit_registry": True, } - if __utils__["reg.key_exists"](**kwargs): - for sub_key in __utils__["reg.list_keys"](**kwargs): + if salt.utils.win_reg.key_exists(**kwargs): + for sub_key in salt.utils.win_reg.list_keys(**kwargs): kwargs["sub_key"] = sub_key if skip_component(**kwargs): continue @@ -814,15 +817,15 @@ def add_software(hive, key, sub_key, use_32bit_registry): "key": product_key.format(user_guid), "use_32bit_registry": True, } - if __utils__["reg.key_exists"](**kwargs): + if salt.utils.win_reg.key_exists(**kwargs): # While we have the user guid, we're going to check userdata in HKLM - for sub_key_2 in __utils__["reg.list_keys"](**kwargs): + for sub_key_2 in salt.utils.win_reg.list_keys(**kwargs): kwargs = { "hive": "HKLM", "key": user_data_key.format(user_guid, sub_key_2), "use_32bit_registry": True, } - if __utils__["reg.key_exists"](**kwargs): + if salt.utils.win_reg.key_exists(**kwargs): kwargs["sub_key"] = "InstallProperties" if skip_component(**kwargs): continue diff --git a/salt/modules/win_snmp.py b/salt/modules/win_snmp.py index 0fc7775ea6c2..84279951cc50 100644 --- a/salt/modules/win_snmp.py +++ b/salt/modules/win_snmp.py @@ -6,16 +6,17 @@ import logging import salt.utils.platform +import salt.utils.win_reg from salt.exceptions import CommandExecutionError, SaltInvocationError _HKEY = "HKLM" _SNMP_KEY = r"SYSTEM\CurrentControlSet\Services\SNMP\Parameters" -_AGENT_KEY = r"{}\RFC1156Agent".format(_SNMP_KEY) -_COMMUNITIES_KEY = r"{}\ValidCommunities".format(_SNMP_KEY) +_AGENT_KEY = rf"{_SNMP_KEY}\RFC1156Agent" +_COMMUNITIES_KEY = rf"{_SNMP_KEY}\ValidCommunities" _SNMP_GPO_KEY = r"SOFTWARE\Policies\SNMP\Parameters" -_COMMUNITIES_GPO_KEY = r"{}\ValidCommunities".format(_SNMP_GPO_KEY) +_COMMUNITIES_GPO_KEY = rf"{_SNMP_GPO_KEY}\ValidCommunities" _PERMISSION_TYPES = { "None": 1, @@ -46,7 +47,7 @@ def __virtual__(): if not salt.utils.platform.is_windows(): return False, "Module win_snmp: Requires Windows" - if not __utils__["reg.key_exists"](_HKEY, _SNMP_KEY): + if not salt.utils.win_reg.key_exists(_HKEY, _SNMP_KEY): return False, "Module win_snmp: SNMP not installed" return __virtualname__ @@ -102,15 +103,15 @@ def get_agent_settings(): sorted_types = sorted(_SERVICE_TYPES.items(), key=lambda x: (-x[1], x[0])) ret["services"] = list() - ret["contact"] = (__utils__["reg.read_value"](_HKEY, _AGENT_KEY, "sysContact"))[ + ret["contact"] = (salt.utils.win_reg.read_value(_HKEY, _AGENT_KEY, "sysContact"))[ "vdata" ] - ret["location"] = (__utils__["reg.read_value"](_HKEY, _AGENT_KEY, "sysLocation"))[ + ret["location"] = (salt.utils.win_reg.read_value(_HKEY, _AGENT_KEY, "sysLocation"))[ "vdata" ] - current_bitmask = (__utils__["reg.read_value"](_HKEY, _AGENT_KEY, "sysServices"))[ + current_bitmask = (salt.utils.win_reg.read_value(_HKEY, _AGENT_KEY, "sysServices"))[ "vdata" ] @@ -177,13 +178,13 @@ def set_agent_settings(contact=None, location=None, services=None): if contact is not None: if contact != current_settings["contact"]: - __utils__["reg.set_value"]( + salt.utils.win_reg.set_value( _HKEY, _AGENT_KEY, "sysContact", contact, "REG_SZ" ) if location is not None: if location != current_settings["location"]: - __utils__["reg.set_value"]( + salt.utils.win_reg.set_value( _HKEY, _AGENT_KEY, "sysLocation", location, "REG_SZ" ) @@ -195,7 +196,7 @@ def set_agent_settings(contact=None, location=None, services=None): _LOG.debug("Setting sysServices vdata to: %s", vdata) - __utils__["reg.set_value"]( + salt.utils.win_reg.set_value( _HKEY, _AGENT_KEY, "sysServices", vdata, "REG_DWORD" ) @@ -229,7 +230,9 @@ def get_auth_traps_enabled(): salt '*' win_snmp.get_auth_traps_enabled """ - reg_ret = __utils__["reg.read_value"](_HKEY, _SNMP_KEY, "EnableAuthenticationTraps") + reg_ret = salt.utils.win_reg.read_value( + _HKEY, _SNMP_KEY, "EnableAuthenticationTraps" + ) if reg_ret["vdata"] == "(value not set)": return False @@ -260,7 +263,7 @@ def set_auth_traps_enabled(status=True): return True vdata = int(status) - __utils__["reg.set_value"](_HKEY, _SNMP_KEY, vname, vdata, "REG_DWORD") + salt.utils.win_reg.set_value(_HKEY, _SNMP_KEY, vname, vdata, "REG_DWORD") new_status = get_auth_traps_enabled() @@ -302,11 +305,11 @@ def get_community_names(): ret = dict() # Look in GPO settings first - if __utils__["reg.key_exists"](_HKEY, _COMMUNITIES_GPO_KEY): + if salt.utils.win_reg.key_exists(_HKEY, _COMMUNITIES_GPO_KEY): _LOG.debug("Loading communities from Group Policy settings") - current_values = __utils__["reg.list_values"](_HKEY, _COMMUNITIES_GPO_KEY) + current_values = salt.utils.win_reg.list_values(_HKEY, _COMMUNITIES_GPO_KEY) # GPO settings are different in that they do not designate permissions # They are a numbered list of communities like so: @@ -333,7 +336,7 @@ def get_community_names(): _LOG.debug("Loading communities from SNMP settings") - current_values = __utils__["reg.list_values"](_HKEY, _COMMUNITIES_KEY) + current_values = salt.utils.win_reg.list_values(_HKEY, _COMMUNITIES_KEY) # The communities are stored as the community name with a numeric # permission value. Like this (4 = Read Only): @@ -396,7 +399,7 @@ def set_community_names(communities): """ values = dict() - if __utils__["reg.key_exists"](_HKEY, _COMMUNITIES_GPO_KEY): + if salt.utils.win_reg.key_exists(_HKEY, _COMMUNITIES_GPO_KEY): _LOG.debug("Communities on this system are managed by Group Policy") raise CommandExecutionError( "Communities on this system are managed by Group Policy" @@ -426,7 +429,7 @@ def set_community_names(communities): if current_vname in values: # Modify existing communities that have a different permission value. if current_communities[current_vname] != values[current_vname]: - __utils__["reg.set_value"]( + salt.utils.win_reg.set_value( _HKEY, _COMMUNITIES_KEY, current_vname, @@ -435,12 +438,12 @@ def set_community_names(communities): ) else: # Remove current communities that weren't provided. - __utils__["reg.delete_value"](_HKEY, _COMMUNITIES_KEY, current_vname) + salt.utils.win_reg.delete_value(_HKEY, _COMMUNITIES_KEY, current_vname) # Create any new communities. for vname in values: if vname not in current_communities: - __utils__["reg.set_value"]( + salt.utils.win_reg.set_value( _HKEY, _COMMUNITIES_KEY, vname, values[vname], "REG_DWORD" ) diff --git a/salt/modules/win_useradd.py b/salt/modules/win_useradd.py index e557ffd8113c..c45ec9e0fae3 100644 --- a/salt/modules/win_useradd.py +++ b/salt/modules/win_useradd.py @@ -30,6 +30,7 @@ import salt.utils.args import salt.utils.dateutils import salt.utils.platform +import salt.utils.win_reg import salt.utils.winapi from salt.exceptions import CommandExecutionError @@ -250,7 +251,7 @@ def update( try: dt_obj = salt.utils.dateutils.date_cast(expiration_date) except (ValueError, RuntimeError): - return "Invalid Date/Time Format: {}".format(expiration_date) + return f"Invalid Date/Time Format: {expiration_date}" user_info["acct_expires"] = time.mktime(dt_obj.timetuple()) if expired is not None: if expired: @@ -467,7 +468,7 @@ def addgroup(name, group): if group in user["groups"]: return True - cmd = 'net localgroup "{}" {} /add'.format(group, name) + cmd = f'net localgroup "{group}" {name} /add' ret = __salt__["cmd.run_all"](cmd, python_shell=True) return ret["retcode"] == 0 @@ -502,7 +503,7 @@ def removegroup(name, group): if group not in user["groups"]: return True - cmd = 'net localgroup "{}" {} /delete'.format(group, name) + cmd = f'net localgroup "{group}" {name} /delete' ret = __salt__["cmd.run_all"](cmd, python_shell=True) return ret["retcode"] == 0 @@ -633,14 +634,14 @@ def chgroups(name, groups, append=True): for group in ugrps: group = shlex.quote(group).lstrip("'").rstrip("'") if group not in groups: - cmd = 'net localgroup "{}" {} /delete'.format(group, name) + cmd = f'net localgroup "{group}" {name} /delete' __salt__["cmd.run_all"](cmd, python_shell=True) for group in groups: if group in ugrps: continue group = shlex.quote(group).lstrip("'").rstrip("'") - cmd = 'net localgroup "{}" {} /add'.format(group, name) + cmd = f'net localgroup "{group}" {name} /add' out = __salt__["cmd.run_all"](cmd, python_shell=True) if out["retcode"] != 0: log.error(out["stdout"]) @@ -772,9 +773,9 @@ def _get_userprofile_from_registry(user, sid): Returns: str: Profile directory """ - profile_dir = __utils__["reg.read_value"]( + profile_dir = salt.utils.win_reg.read_value( "HKEY_LOCAL_MACHINE", - "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ProfileList\\{}".format(sid), + f"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ProfileList\\{sid}", "ProfileImagePath", )["vdata"] log.debug('user %s with sid=%s profile is located at "%s"', user, sid, profile_dir) @@ -901,12 +902,12 @@ def rename(name, new_name): # Load information for the current name current_info = info(name) if not current_info: - raise CommandExecutionError("User '{}' does not exist".format(name)) + raise CommandExecutionError(f"User '{name}' does not exist") # Look for an existing user with the new name new_info = info(new_name) if new_info: - raise CommandExecutionError("User '{}' already exists".format(new_name)) + raise CommandExecutionError(f"User '{new_name}' already exists") # Rename the user account # Connect to WMI @@ -917,7 +918,7 @@ def rename(name, new_name): try: user = c.Win32_UserAccount(Name=name)[0] except IndexError: - raise CommandExecutionError("User '{}' does not exist".format(name)) + raise CommandExecutionError(f"User '{name}' does not exist") # Rename the user result = user.Rename(new_name)[0] diff --git a/salt/states/environ.py b/salt/states/environ.py index fb495d1af441..e82d3c54db68 100644 --- a/salt/states/environ.py +++ b/salt/states/environ.py @@ -2,11 +2,10 @@ Support for getting and setting the environment variables of the current salt process. """ - - import os import salt.utils.platform +import salt.utils.win_reg def __virtual__(): @@ -131,7 +130,7 @@ def key_exists(): r" Manager\Environment" ) - out = __utils__["reg.read_value"]( + out = salt.utils.win_reg.read_value( permanent_hive, permanent_key, _norm_key(key) ) return out["success"] is True diff --git a/salt/states/reg.py b/salt/states/reg.py index 97359c01d843..1f3c2e9569f6 100644 --- a/salt/states/reg.py +++ b/salt/states/reg.py @@ -72,6 +72,8 @@ import logging import salt.utils.stringutils +import salt.utils.win_dacl +import salt.utils.win_reg log = logging.getLogger(__name__) @@ -80,31 +82,11 @@ def __virtual__(): """ Load this state if the reg module exists """ - if "reg.read_value" not in __utils__: + if salt.utils.win_reg.HAS_WINDOWS_MODULES is False: return ( False, - "reg state module failed to load: missing util function: reg.read_value", + "The salt.utils.win_reg module could not be imported", ) - - if "reg.set_value" not in __utils__: - return ( - False, - "reg state module failed to load: missing util function: reg.set_value", - ) - - if "reg.delete_value" not in __utils__: - return ( - False, - "reg state module failed to load: missing util function: reg.delete_value", - ) - - if "reg.delete_key_recursive" not in __utils__: - return ( - False, - "reg state module failed to load: " - "missing util function: reg.delete_key_recursive", - ) - return "reg" @@ -396,12 +378,12 @@ def present( hive, key = _parse_key(name) # Determine what to do - reg_current = __utils__["reg.read_value"]( + reg_current = salt.utils.win_reg.read_value( hive=hive, key=key, vname=vname, use_32bit_registry=use_32bit_registry ) # Cast the vdata according to the vtype - vdata_decoded = __utils__["reg.cast_vdata"](vdata=vdata, vtype=vtype) + vdata_decoded = salt.utils.win_reg.cast_vdata(vdata=vdata, vtype=vtype) # Check if the key already exists # If so, check perms @@ -411,7 +393,7 @@ def present( salt.utils.stringutils.to_unicode(vname, "utf-8") if vname else "(Default)", salt.utils.stringutils.to_unicode(name, "utf-8"), ) - return __utils__["dacl.check_perms"]( + return salt.utils.win_dacl.check_perms( obj_name="\\".join([hive, key]), obj_type="registry32" if use_32bit_registry else "registry", ret=ret, @@ -420,10 +402,11 @@ def present( deny_perms=win_deny_perms, inheritance=win_inheritance, reset=win_perms_reset, + test_mode=__opts__.get("test", False), ) add_change = { - "Key": r"{}\{}".format(hive, key), + "Key": rf"{hive}\{key}", "Entry": "{}".format( salt.utils.stringutils.to_unicode(vname, "utf-8") if vname else "(Default)" ), @@ -440,7 +423,7 @@ def present( return ret # Configure the value - ret["result"] = __utils__["reg.set_value"]( + ret["result"] = salt.utils.win_reg.set_value( hive=hive, key=key, vname=vname, @@ -451,13 +434,13 @@ def present( if not ret["result"]: ret["changes"] = {} - ret["comment"] = r"Failed to add {} to {}\{}".format(vname, hive, key) + ret["comment"] = rf"Failed to add {vname} to {hive}\{key}" else: ret["changes"] = {"reg": {"Added": add_change}} - ret["comment"] = r"Added {} to {}\{}".format(vname, hive, key) + ret["comment"] = rf"Added {vname} to {hive}\{key}" if ret["result"]: - ret = __utils__["dacl.check_perms"]( + ret = salt.utils.win_dacl.check_perms( obj_name="\\".join([hive, key]), obj_type="registry32" if use_32bit_registry else "registry", ret=ret, @@ -466,6 +449,7 @@ def present( deny_perms=win_deny_perms, inheritance=win_inheritance, reset=win_perms_reset, + test_mode=__opts__.get("test", False), ) return ret @@ -517,15 +501,15 @@ def absent(name, vname=None, use_32bit_registry=False): hive, key = _parse_key(name) # Determine what to do - reg_check = __utils__["reg.read_value"]( + reg_check = salt.utils.win_reg.read_value( hive=hive, key=key, vname=vname, use_32bit_registry=use_32bit_registry ) if not reg_check["success"] or reg_check["vdata"] == "(value not set)": - ret["comment"] = "{} is already absent".format(name) + ret["comment"] = f"{name} is already absent" return ret remove_change = { - "Key": r"{}\{}".format(hive, key), + "Key": rf"{hive}\{key}", "Entry": "{}".format(vname if vname else "(Default)"), } @@ -536,15 +520,15 @@ def absent(name, vname=None, use_32bit_registry=False): return ret # Delete the value - ret["result"] = __utils__["reg.delete_value"]( + ret["result"] = salt.utils.win_reg.delete_value( hive=hive, key=key, vname=vname, use_32bit_registry=use_32bit_registry ) if not ret["result"]: ret["changes"] = {} - ret["comment"] = r"Failed to remove {} from {}".format(key, hive) + ret["comment"] = rf"Failed to remove {key} from {hive}" else: ret["changes"] = {"reg": {"Removed": remove_change}} - ret["comment"] = r"Removed {} from {}".format(key, hive) + ret["comment"] = rf"Removed {key} from {hive}" return ret @@ -595,13 +579,13 @@ def key_absent(name, use_32bit_registry=False): hive, key = _parse_key(name) # Determine what to do - if not __utils__["reg.read_value"]( + if not salt.utils.win_reg.read_value( hive=hive, key=key, use_32bit_registry=use_32bit_registry )["success"]: - ret["comment"] = "{} is already absent".format(name) + ret["comment"] = f"{name} is already absent" return ret - ret["changes"] = {"reg": {"Removed": {"Key": r"{}\{}".format(hive, key)}}} + ret["changes"] = {"reg": {"Removed": {"Key": rf"{hive}\{key}"}}} # Check for test option if __opts__["test"]: @@ -609,14 +593,14 @@ def key_absent(name, use_32bit_registry=False): return ret # Delete the value - __utils__["reg.delete_key_recursive"]( + salt.utils.win_reg.delete_key_recursive( hive=hive, key=key, use_32bit_registry=use_32bit_registry ) - if __utils__["reg.read_value"]( + if salt.utils.win_reg.read_value( hive=hive, key=key, use_32bit_registry=use_32bit_registry )["success"]: ret["result"] = False ret["changes"] = {} - ret["comment"] = "Failed to remove registry key {}".format(name) + ret["comment"] = f"Failed to remove registry key {name}" return ret diff --git a/salt/states/win_dns_client.py b/salt/states/win_dns_client.py index 9afa0faf3689..e0e7deab4f74 100644 --- a/salt/states/win_dns_client.py +++ b/salt/states/win_dns_client.py @@ -2,6 +2,8 @@ Module for configuring DNS Client on Windows systems """ +import salt.utils.win_reg + def __virtual__(): """ @@ -53,7 +55,7 @@ def dns_exists(name, servers=None, interface="Local Area Connection", replace=Fa # Do nothing is already configured configured_list = __salt__["win_dns_client.get_dns_servers"](interface) if configured_list == servers: - ret["comment"] = "{} are already configured".format(servers) + ret["comment"] = f"{servers} are already configured" ret["changes"] = {} ret["result"] = True return ret @@ -91,7 +93,7 @@ def dns_exists(name, servers=None, interface="Local Area Connection", replace=Fa if not __salt__["win_dns_client.rm_dns"](server, interface): ret[ "comment" - ] = "Failed to remove {} from DNS server list".format(server) + ] = f"Failed to remove {server} from DNS server list" ret["result"] = False return ret else: @@ -109,7 +111,7 @@ def dns_dhcp(name, interface="Local Area Connection"): # Check the config config = __salt__["win_dns_client.get_dns_config"](interface) if config == "dhcp": - ret["comment"] = "{} already configured with DNS from DHCP".format(interface) + ret["comment"] = f"{interface} already configured with DNS from DHCP" return ret else: ret["changes"] = {"dns": "configured from DHCP"} @@ -185,14 +187,14 @@ def primary_suffix(name, suffix=None, updates=False): }, } - reg_data["suffix"]["old"] = __utils__["reg.read_value"]( + reg_data["suffix"]["old"] = salt.utils.win_reg.read_value( reg_data["suffix"]["hive"], reg_data["suffix"]["key"], reg_data["suffix"]["vname"], )["vdata"] reg_data["updates"]["old"] = bool( - __utils__["reg.read_value"]( + salt.utils.win_reg.read_value( reg_data["updates"]["hive"], reg_data["updates"]["key"], reg_data["updates"]["vname"], @@ -208,7 +210,7 @@ def primary_suffix(name, suffix=None, updates=False): return ret # Changes to update policy needed else: - ret["comment"] = "{} suffix updates".format(updates_operation) + ret["comment"] = f"{updates_operation} suffix updates" ret["changes"] = { "old": {"updates": reg_data["updates"]["old"]}, "new": {"updates": reg_data["updates"]["new"]}, @@ -234,13 +236,13 @@ def primary_suffix(name, suffix=None, updates=False): } # No changes to updates policy needed else: - ret["comment"] = "Updated primary DNS suffix ({})".format(suffix) + ret["comment"] = f"Updated primary DNS suffix ({suffix})" ret["changes"] = { "old": {"suffix": reg_data["suffix"]["old"]}, "new": {"suffix": reg_data["suffix"]["new"]}, } - suffix_result = __utils__["reg.set_value"]( + suffix_result = salt.utils.win_reg.set_value( reg_data["suffix"]["hive"], reg_data["suffix"]["key"], reg_data["suffix"]["vname"], @@ -248,7 +250,7 @@ def primary_suffix(name, suffix=None, updates=False): reg_data["suffix"]["vtype"], ) - updates_result = __utils__["reg.set_value"]( + updates_result = salt.utils.win_reg.set_value( reg_data["updates"]["hive"], reg_data["updates"]["key"], reg_data["updates"]["vname"], diff --git a/salt/states/win_lgpo_reg.py b/salt/states/win_lgpo_reg.py index 8377817a1985..015f36cabf7f 100644 --- a/salt/states/win_lgpo_reg.py +++ b/salt/states/win_lgpo_reg.py @@ -55,6 +55,7 @@ """ import salt.utils.data import salt.utils.platform +import salt.utils.win_reg __virtualname__ = "lgpo_reg" @@ -82,7 +83,7 @@ def _get_current(key, name, policy_class): pol = __salt__["lgpo_reg.get_value"]( key=key, v_name=name, policy_class=policy_class ) - reg_raw = __utils__["reg.read_value"](hive=hive, key=key, vname=name) + reg_raw = salt.utils.win_reg.read_value(hive=hive, key=key, vname=name) reg = {} if reg_raw["vdata"] is not None: @@ -251,7 +252,7 @@ def value_disabled(name, key, policy_class="Machine"): old = _get_current(key=key, name=name, policy_class=policy_class) - pol_correct = old["pol"].get("data", "") == "**del.{}".format(name) + pol_correct = old["pol"].get("data", "") == f"**del.{name}" reg_correct = old["reg"] == {} if pol_correct and reg_correct: @@ -273,7 +274,7 @@ def value_disabled(name, key, policy_class="Machine"): new = _get_current(key=key, name=name, policy_class=policy_class) - pol_correct = new["pol"].get("data", "") == "**del.{}".format(name) + pol_correct = new["pol"].get("data", "") == f"**del.{name}" reg_correct = new["reg"] == {} if pol_correct and reg_correct: diff --git a/salt/utils/user.py b/salt/utils/user.py index 97636674430a..db3f8aec41ed 100644 --- a/salt/utils/user.py +++ b/salt/utils/user.py @@ -2,8 +2,6 @@ Functions for querying and modifying a user account and the groups to which it belongs. """ - - import ctypes import getpass import logging @@ -158,13 +156,13 @@ def get_specific_user(): user = get_user() if salt.utils.platform.is_windows(): if _win_current_user_is_admin(): - return "sudo_{}".format(user) + return f"sudo_{user}" else: env_vars = ("SUDO_USER",) if user == "root": for evar in env_vars: if evar in os.environ: - return "sudo_{}".format(os.environ[evar]) + return f"sudo_{os.environ[evar]}" return user @@ -182,7 +180,7 @@ def chugid(runas, group=None): target_pw_gid = grp.getgrnam(group).gr_gid except KeyError as err: raise CommandExecutionError( - "Failed to fetch the GID for {}. Error: {}".format(group, err) + f"Failed to fetch the GID for {group}. Error: {err}" ) else: target_pw_gid = uinfo.pw_gid diff --git a/salt/utils/win_chcp.py b/salt/utils/win_chcp.py index 2f4d2891267d..c71a8c523417 100644 --- a/salt/utils/win_chcp.py +++ b/salt/utils/win_chcp.py @@ -18,17 +18,6 @@ HAS_WIN32 = False -# Although utils are often directly imported, it is also possible to use the loader. -def __virtual__(): - """ - Only load if Win32 Libraries are installed - """ - if not HAS_WIN32: - return False, "This utility requires pywin32" - - return "win_chcp" - - @contextmanager def chcp(page_id, raise_error=False): """ @@ -53,7 +42,7 @@ def chcp(page_id, raise_error=False): try: page_id = int(page_id) except ValueError: - error = "The `page_id` needs to be an integer, not {}".format(type(page_id)) + error = f"The `page_id` needs to be an integer, not {type(page_id)}" if raise_error: raise CodePageError(error) log.error(error) @@ -98,7 +87,7 @@ def get_codepage_id(raise_error=False): return win32console.GetConsoleCP() except pywintypes.error as exc: _, _, msg = exc.args - error = "Failed to get the windows code page: {}".format(msg) + error = f"Failed to get the windows code page: {msg}" if raise_error: raise CodePageError(error) else: @@ -129,7 +118,7 @@ def set_codepage_id(page_id, raise_error=False): try: page_id = int(page_id) except ValueError: - error = "The `page_id` needs to be an integer, not {}".format(type(page_id)) + error = f"The `page_id` needs to be an integer, not {type(page_id)}" if raise_error: raise CodePageError(error) log.error(error) @@ -139,7 +128,7 @@ def set_codepage_id(page_id, raise_error=False): return get_codepage_id(raise_error=raise_error) except pywintypes.error as exc: _, _, msg = exc.args - error = "Failed to set the windows code page: {}".format(msg) + error = f"Failed to set the windows code page: {msg}" if raise_error: raise CodePageError(error) else: diff --git a/salt/utils/win_dacl.py b/salt/utils/win_dacl.py index ec16f7a22c68..92a9722db9b4 100644 --- a/salt/utils/win_dacl.py +++ b/salt/utils/win_dacl.py @@ -157,21 +157,6 @@ log = logging.getLogger(__name__) -__virtualname__ = "dacl" - - -def __virtual__(): - """ - Only load if Win32 Libraries are installed - """ - if not salt.utils.platform.is_windows(): - return False, "win_dacl: Requires Windows" - - if not HAS_WIN32: - return False, "win_dacl: Requires pywin32" - - return __virtualname__ - def flags(instantiated=True): """ @@ -496,9 +481,7 @@ def __init__(self, obj_name=None, obj_type="file"): """ # Validate obj_type if obj_type.lower() not in self.obj_type: - raise SaltInvocationError( - 'Invalid "obj_type" passed: {}'.format(obj_type) - ) + raise SaltInvocationError(f'Invalid "obj_type" passed: {obj_type}') self.dacl_type = obj_type.lower() @@ -514,7 +497,7 @@ def __init__(self, obj_name=None, obj_type="file"): ) except pywintypes.error as exc: if "The system cannot find" in exc.strerror: - msg = "System cannot find {}".format(obj_name) + msg = f"System cannot find {obj_name}" log.exception(msg) raise CommandExecutionError(msg) raise @@ -588,9 +571,7 @@ def get_reg_name(self, obj_name): valid_hive = hives[passed_hive.upper()] except KeyError: log.exception("Invalid Registry Hive: %s", passed_hive) - raise CommandExecutionError( - "Invalid Registry Hive: {}".format(passed_hive) - ) + raise CommandExecutionError(f"Invalid Registry Hive: {passed_hive}") reg.insert(0, valid_hive) @@ -632,7 +613,7 @@ def add_ace(self, principal, access_mode, permissions, applies_to): if applies_to not in self.ace_prop[self.dacl_type]: raise SaltInvocationError( - "Invalid 'applies_to' for type {}".format(self.dacl_type) + f"Invalid 'applies_to' for type {self.dacl_type}" ) if self.dacl is None: @@ -644,7 +625,7 @@ def add_ace(self, principal, access_mode, permissions, applies_to): try: perm_flag = self.ace_perms[self.dacl_type]["basic"][permissions] except KeyError as exc: - msg = "Invalid permission specified: {}".format(permissions) + msg = f"Invalid permission specified: {permissions}" log.exception(msg) raise CommandExecutionError(msg, exc) else: @@ -652,12 +633,12 @@ def add_ace(self, principal, access_mode, permissions, applies_to): try: perm_flag |= self.ace_perms[self.dacl_type]["advanced"][perm] except KeyError as exc: - msg = "Invalid permission specified: {}".format(perm) + msg = f"Invalid permission specified: {perm}" log.exception(msg) raise CommandExecutionError(msg, exc) if access_mode.lower() not in ["grant", "deny"]: - raise SaltInvocationError("Invalid Access Mode: {}".format(access_mode)) + raise SaltInvocationError(f"Invalid Access Mode: {access_mode}") # Add ACE to the DACL # Grant or Deny @@ -686,11 +667,9 @@ def add_ace(self, principal, access_mode, permissions, applies_to): ) else: log.exception("Invalid access mode: %s", access_mode) - raise SaltInvocationError( - "Invalid access mode: {}".format(access_mode) - ) + raise SaltInvocationError(f"Invalid access mode: {access_mode}") except Exception as exc: # pylint: disable=broad-except - return False, "Error: {}".format(exc) + return False, f"Error: {exc}" return True @@ -945,7 +924,7 @@ def _ace_to_dict(self, ace): # If still nothing, it must be undefined if not ace_perms: - ace_perms = ["Undefined Permission: {}".format(ace[1])] + ace_perms = [f"Undefined Permission: {ace[1]}"] return ( principal, @@ -1001,7 +980,7 @@ def rm_ace(self, principal, ace_type="all"): offset += 1 if not ret: - ret = ["ACE not found for {}".format(principal)] + ret = [f"ACE not found for {principal}"] return ret @@ -1100,7 +1079,7 @@ def save(self, obj_name, protected=None): ) except pywintypes.error as exc: raise CommandExecutionError( - "Failed to set permissions: {}".format(obj_name), exc.strerror + f"Failed to set permissions: {obj_name}", exc.strerror ) return True @@ -1146,7 +1125,7 @@ def get_sid(principal): sid = win32security.ConvertStringSidToSid(sid) except pywintypes.error: log.exception("Invalid user/group or sid: %s", principal) - raise CommandExecutionError("Invalid user/group or sid: {}".format(principal)) + raise CommandExecutionError(f"Invalid user/group or sid: {principal}") except TypeError: raise CommandExecutionError @@ -1189,7 +1168,7 @@ def get_sid_string(principal): return win32security.ConvertSidToStringSid(principal) except pywintypes.error: log.exception("Invalid principal %s", principal) - raise CommandExecutionError("Invalid principal {}".format(principal)) + raise CommandExecutionError(f"Invalid principal {principal}") def get_name(principal): @@ -1249,7 +1228,7 @@ def get_name(principal): # https://docs.microsoft.com/en-us/previous-versions/technet-magazine/cc138011(v=msdn.10) # https://docs.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2008-R2-and-2008/dd548356(v=ws.10) if str_sid.startswith("S-1-5-80"): - name = "NT Service\\{}".format(name) + name = f"NT Service\\{name}" return name except (pywintypes.error, TypeError) as exc: @@ -1261,10 +1240,10 @@ def get_name(principal): # All capability SIDs begin with `S-1-15-3`, so we'll only throw an # error when the sid does not begin with `S-1-15-3` if not str_sid.startswith("S-1-15-3"): - message = 'Error resolving "{}"'.format(principal) + message = f'Error resolving "{principal}"' if type(exc) == pywintypes.error: win_error = win32api.FormatMessage(exc.winerror).rstrip("\n") - message = "{}: {}".format(message, win_error) + message = f"{message}: {win_error}" log.exception(message) raise CommandExecutionError(message, exc) @@ -1326,7 +1305,7 @@ def get_owner(obj_name, obj_type="file"): try: obj_type_flag = flags().obj_type[obj_type.lower()] except KeyError: - raise SaltInvocationError('Invalid "obj_type" passed: {}'.format(obj_type)) + raise SaltInvocationError(f'Invalid "obj_type" passed: {obj_type}') if obj_type in ["registry", "registry32"]: obj_name = dacl().get_reg_name(obj_name) @@ -1348,7 +1327,7 @@ def get_owner(obj_name, obj_type="file"): else: log.exception("Failed to get the owner: %s", obj_name) raise CommandExecutionError( - "Failed to get owner: {}".format(obj_name), exc.strerror + f"Failed to get owner: {obj_name}", exc.strerror ) return get_name(owner_sid) @@ -1411,7 +1390,7 @@ def get_primary_group(obj_name, obj_type="file"): try: obj_type_flag = flags().obj_type[obj_type.lower()] except KeyError: - raise SaltInvocationError('Invalid "obj_type" passed: {}'.format(obj_type)) + raise SaltInvocationError(f'Invalid "obj_type" passed: {obj_type}') if "registry" in obj_type.lower(): obj_name = dacl().get_reg_name(obj_name) @@ -1434,7 +1413,7 @@ def get_primary_group(obj_name, obj_type="file"): else: log.exception("Failed to get the primary group: %s", obj_name) raise CommandExecutionError( - "Failed to get primary group: {}".format(obj_name), exc.strerror + f"Failed to get primary group: {obj_name}", exc.strerror ) return get_name(win32security.ConvertSidToStringSid(primary_group_gid)) @@ -1476,7 +1455,7 @@ def set_owner(obj_name, principal, obj_type="file"): # Validate obj_type if obj_type.lower() not in obj_flags.obj_type: - raise SaltInvocationError('Invalid "obj_type" passed: {}'.format(obj_type)) + raise SaltInvocationError(f'Invalid "obj_type" passed: {obj_type}') if "registry" in obj_type.lower(): obj_name = dacl().get_reg_name(obj_name) @@ -1513,9 +1492,7 @@ def set_owner(obj_name, principal, obj_type="file"): ) except pywintypes.error as exc: log.exception("Failed to make %s the owner: %s", principal, exc) - raise CommandExecutionError( - "Failed to set owner: {}".format(obj_name), exc.strerror - ) + raise CommandExecutionError(f"Failed to set owner: {obj_name}", exc.strerror) return True @@ -1561,7 +1538,7 @@ def set_primary_group(obj_name, principal, obj_type="file"): # Validate obj_type if obj_type.lower() not in obj_flags.obj_type: - raise SaltInvocationError('Invalid "obj_type" passed: {}'.format(obj_type)) + raise SaltInvocationError(f'Invalid "obj_type" passed: {obj_type}') if "registry" in obj_type.lower(): obj_name = dacl().get_reg_name(obj_name) @@ -1599,7 +1576,7 @@ def set_primary_group(obj_name, principal, obj_type="file"): except pywintypes.error as exc: log.exception("Failed to make %s the primary group: %s", principal, exc) raise CommandExecutionError( - "Failed to set primary group: {}".format(obj_name), exc.strerror + f"Failed to set primary group: {obj_name}", exc.strerror ) return True @@ -1819,9 +1796,7 @@ def has_permission( """ # Validate access_mode if access_mode.lower() not in ["grant", "deny"]: - raise SaltInvocationError( - 'Invalid "access_mode" passed: {}'.format(access_mode) - ) + raise SaltInvocationError(f'Invalid "access_mode" passed: {access_mode}') access_mode = access_mode.lower() # Get the DACL @@ -1838,7 +1813,7 @@ def has_permission( obj_dacl.ace_perms[obj_type]["advanced"].get(permission.lower(), False), ) if not chk_flag: - raise SaltInvocationError('Invalid "permission" passed: {}'.format(permission)) + raise SaltInvocationError(f'Invalid "permission" passed: {permission}') # Check each ace for sid and type cur_flag = None @@ -1919,9 +1894,7 @@ def has_permissions( # Validate access_mode if access_mode.lower() not in ["grant", "deny"]: - raise SaltInvocationError( - 'Invalid "access_mode" passed: {}'.format(access_mode) - ) + raise SaltInvocationError(f'Invalid "access_mode" passed: {access_mode}') access_mode = access_mode.lower() # Get the DACL @@ -1940,9 +1913,7 @@ def has_permissions( obj_dacl.ace_perms[obj_type]["advanced"].get(permission.lower(), False), ) if not chk_flag: - raise SaltInvocationError( - 'Invalid "permission" passed: {}'.format(permission) - ) + raise SaltInvocationError(f'Invalid "permission" passed: {permission}') # Check each ace for sid and type cur_flag = None @@ -1998,7 +1969,7 @@ def set_inheritance(obj_name, enabled, obj_type="file", clear=False): """ if obj_type not in ["file", "registry", "registry32"]: raise SaltInvocationError( - "obj_type called with incorrect parameter: {}".format(obj_name) + f"obj_type called with incorrect parameter: {obj_name}" ) if clear: @@ -2161,7 +2132,7 @@ def copy_security( try: obj_type_flag = flags().obj_type[obj_type.lower()] except KeyError: - raise SaltInvocationError('Invalid "obj_type" passed: {}'.format(obj_type)) + raise SaltInvocationError(f'Invalid "obj_type" passed: {obj_type}') security_flags = 0 if copy_owner: @@ -2214,9 +2185,7 @@ def copy_security( target, obj_type_flag, security_flags, sd_sid, sd_gid, sd_dacl, sd_sacl ) except pywintypes.error as exc: - raise CommandExecutionError( - "Failed to set security info: {}".format(exc.strerror) - ) + raise CommandExecutionError(f"Failed to set security info: {exc.strerror}") return True @@ -2254,7 +2223,7 @@ def _check_perms(obj_name, obj_type, new_perms, access_mode, ret, test_mode=Fals dict: A dictionary of return data as expected by the state system """ access_mode = access_mode.lower() - perms_label = "{}_perms".format(access_mode) + perms_label = f"{access_mode}_perms" cur_perms = get_permissions(obj_name=obj_name, obj_type=obj_type) changes = {} for user in new_perms: @@ -2403,38 +2372,33 @@ def check_perms( .. code-block:: bash - # You have to use __utils__ in order for __opts__ to be available - # To see changes to ``C:\\Temp`` if the 'Users' group is given 'read & execute' permissions. - __utils__['dacl.check_perms'](obj_name='C:\\Temp', - obj_type='file', - owner='Administrators', - grant_perms={ - 'Users': { - 'perms': 'read_execute' - } - }) + salt.utils.win_dacl.check_perms(obj_name='C:\\Temp', + obj_type='file', + owner='Administrators', + grant_perms={ + 'Users': { + 'perms': 'read_execute' + } + }) # Specify advanced attributes with a list - __utils__['dacl.check_perms'](obj_name='C:\\Temp', - obj_type='file', - owner='Administrators', - grant_perms={ - 'jsnuffy': { - 'perms': [ - 'read_attributes', - 'read_ea' - ], - 'applies_to': 'files_only' - } - }) + salt.utils.win_dacl.check_perms(obj_name='C:\\Temp', + obj_type='file', + owner='Administrators', + grant_perms={ + 'jsnuffy': { + 'perms': [ + 'read_attributes', + 'read_ea' + ], + 'applies_to': 'files_only' + } + }) """ - if test_mode is None: - test_mode = __opts__["test"] - # Validate obj_type if obj_type.lower() not in flags().obj_type: - raise SaltInvocationError('Invalid "obj_type" passed: {}'.format(obj_type)) + raise SaltInvocationError(f'Invalid "obj_type" passed: {obj_type}') obj_type = obj_type.lower() @@ -2460,9 +2424,7 @@ def check_perms( ret["changes"]["owner"] = owner except CommandExecutionError: ret["result"] = False - ret["comment"].append( - 'Failed to change owner to "{}"'.format(owner) - ) + ret["comment"].append(f'Failed to change owner to "{owner}"') # Check inheritance if inheritance is not None: diff --git a/salt/utils/win_dotnet.py b/salt/utils/win_dotnet.py index 65325da75c3c..b9ad50cb0f28 100644 --- a/salt/utils/win_dotnet.py +++ b/salt/utils/win_dotnet.py @@ -3,25 +3,9 @@ .. versionadded:: 3001 """ - -import salt.utils.platform import salt.utils.win_reg as win_reg from salt.utils.versions import Version -__virtualname__ = "dotnet" - - -# Although utils are often directly imported, it is also possible to use the -# loader. -def __virtual__(): - """ - Only load if platform is Windows - """ - if not salt.utils.platform.is_windows(): - return False, "This utility only works on Windows" - - return __virtualname__ - def versions(): """ @@ -98,12 +82,12 @@ def dotnet_45_plus_versions(release): else: continue - service_pack = " SP{}".format(sp) if sp != "N/A" else "" + service_pack = f" SP{sp}" if sp != "N/A" else "" return_dict["versions"].append(version) return_dict["details"][ver_key] = { "version": version, "service_pack": sp, - "full": "{}{}".format(version, service_pack), + "full": f"{version}{service_pack}", } return return_dict diff --git a/salt/utils/win_functions.py b/salt/utils/win_functions.py index 97e3e0878a21..8ca86c39f718 100644 --- a/salt/utils/win_functions.py +++ b/salt/utils/win_functions.py @@ -22,18 +22,6 @@ HAS_WIN32 = False -# Although utils are often directly imported, it is also possible to use the -# loader. -def __virtual__(): - """ - Only load if Win32 Libraries are installed - """ - if not HAS_WIN32: - return False, "This utility requires pywin32" - - return "win_functions" - - def get_parent_pid(): """ This is a monkey patch for os.getppid. Used in: @@ -135,7 +123,7 @@ def get_sid_from_name(name): try: sid = win32security.LookupAccountName(None, name)[0] except pywintypes.error as exc: - raise CommandExecutionError("User {} not found: {}".format(name, exc)) + raise CommandExecutionError(f"User {name} not found: {exc}") return win32security.ConvertSidToStringSid(sid) @@ -166,7 +154,7 @@ def get_current_user(with_domain=True): elif not with_domain: user_name = win32api.GetUserName() except pywintypes.error as exc: - raise CommandExecutionError("Failed to get current user: {}".format(exc)) + raise CommandExecutionError(f"Failed to get current user: {exc}") if not user_name: return False @@ -253,7 +241,7 @@ def escape_for_cmd_exe(arg): meta_re = re.compile( "(" + "|".join(re.escape(char) for char in list(meta_chars)) + ")" ) - meta_map = {char: "^{}".format(char) for char in meta_chars} + meta_map = {char: f"^{char}" for char in meta_chars} def escape_meta_chars(m): char = m.group(1) diff --git a/salt/utils/win_lgpo_auditpol.py b/salt/utils/win_lgpo_auditpol.py index e155ce0000f9..538a01fd316a 100644 --- a/salt/utils/win_lgpo_auditpol.py +++ b/salt/utils/win_lgpo_auditpol.py @@ -69,9 +69,8 @@ from salt.exceptions import CommandExecutionError log = logging.getLogger(__name__) -__virtualname__ = "auditpol" -categories = [ +CATEGORIES = ( "Account Logon", "Account Management", "Detailed Tracking", @@ -81,9 +80,9 @@ "Policy Change", "Privilege Use", "System", -] +) -settings = { +SETTINGS = { "No Auditing": "/success:disable /failure:disable", "Success": "/success:enable /failure:disable", "Failure": "/success:disable /failure:enable", @@ -91,18 +90,6 @@ } -# Although utils are often directly imported, it is also possible to use the -# loader. -def __virtual__(): - """ - Only load if on a Windows system - """ - if not salt.utils.platform.is_windows(): - return False, "This utility only available on Windows" - - return __virtualname__ - - def _auditpol_cmd(cmd): """ Helper function for running the auditpol command @@ -116,11 +103,11 @@ def _auditpol_cmd(cmd): Raises: CommandExecutionError: If the command encounters an error """ - ret = salt.modules.cmdmod.run_all(cmd="auditpol {}".format(cmd), python_shell=True) + ret = salt.modules.cmdmod.run_all(cmd=f"auditpol {cmd}", python_shell=True) if ret["retcode"] == 0: return ret["stdout"].splitlines() - msg = "Error executing auditpol command: {}\n".format(cmd) + msg = f"Error executing auditpol command: {cmd}\n" msg += "\n".join(ret["stdout"]) raise CommandExecutionError(msg) @@ -172,10 +159,10 @@ def get_settings(category="All"): # Parameter validation if category.lower() in ["all", "*"]: category = "*" - elif category.lower() not in [x.lower() for x in categories]: - raise KeyError('Invalid category: "{}"'.format(category)) + elif category.lower() not in [x.lower() for x in CATEGORIES]: + raise KeyError(f'Invalid category: "{category}"') - cmd = '/get /category:"{}"'.format(category) + cmd = f'/get /category:"{category}"' results = _auditpol_cmd(cmd) ret = {} @@ -213,13 +200,13 @@ def get_setting(name): for setting in current_settings: if name.lower() == setting.lower(): return current_settings[setting] - raise KeyError("Invalid name: {}".format(name)) + raise KeyError(f"Invalid name: {name}") def _get_valid_names(): if "auditpol.valid_names" not in __context__: settings = get_settings(category="All") - __context__["auditpol.valid_names"] = [k.lower() for k in settings] + __context__["auditpol.valid_names"] = [k.lower() for k in SETTINGS] return __context__["auditpol.valid_names"] @@ -264,13 +251,13 @@ def set_setting(name, value): """ # Input validation if name.lower() not in _get_valid_names(): - raise KeyError("Invalid name: {}".format(name)) - for setting in settings: + raise KeyError(f"Invalid name: {name}") + for setting in SETTINGS: if value.lower() == setting.lower(): - cmd = '/set /subcategory:"{}" {}'.format(name, settings[setting]) + cmd = f'/set /subcategory:"{name}" {SETTINGS[setting]}' break else: - raise KeyError("Invalid setting value: {}".format(value)) + raise KeyError(f"Invalid setting value: {value}") _auditpol_cmd(cmd) @@ -298,7 +285,7 @@ def get_auditpol_dump(): with tempfile.NamedTemporaryFile(suffix=".csv") as tmp_file: csv_file = tmp_file.name - cmd = "/backup /file:{}".format(csv_file) + cmd = f"/backup /file:{csv_file}" _auditpol_cmd(cmd) with salt.utils.files.fopen(csv_file) as fp: diff --git a/salt/utils/win_lgpo_netsh.py b/salt/utils/win_lgpo_netsh.py index 7037b9f75dc3..593fd50f4f34 100644 --- a/salt/utils/win_lgpo_netsh.py +++ b/salt/utils/win_lgpo_netsh.py @@ -71,26 +71,18 @@ import re import socket import tempfile +from functools import lru_cache from textwrap import dedent import salt.modules.cmdmod from salt.exceptions import CommandExecutionError log = logging.getLogger(__name__) -__hostname__ = socket.gethostname() -__virtualname__ = "netsh" -# Although utils are often directly imported, it is also possible to use the -# loader. -def __virtual__(): - """ - Only load if on a Windows system - """ - if not salt.utils.platform.is_windows(): - return False, "This utility only available on Windows" - - return __virtualname__ +@lru_cache +def _hostname(): + return socket.gethostname() def _netsh_file(content): @@ -117,34 +109,30 @@ def _netsh_file(content): fp.write(content) try: log.debug("%s:\n%s", fp.name, content) - return salt.modules.cmdmod.run("netsh -f {}".format(fp.name), python_shell=True) + return salt.modules.cmdmod.run(f"netsh -f {fp.name}", python_shell=True) finally: os.remove(fp.name) def _netsh_command(command, store): if store.lower() not in ("local", "lgpo"): - raise ValueError("Incorrect store: {}".format(store)) + raise ValueError(f"Incorrect store: {store}") # set the store for local or lgpo if store.lower() == "local": netsh_script = dedent( - """\ + f"""\ advfirewall set store local - {} - """.format( - command - ) + {command} + """ ) else: netsh_script = dedent( - """\ + f"""\ advfirewall - set store gpo = {} - {} - """.format( - __hostname__, command - ) + set store gpo = {_hostname()} + {command} + """ ) return _netsh_file(content=netsh_script).splitlines() @@ -190,12 +178,12 @@ def get_settings(profile, section, store="local"): """ # validate input if profile.lower() not in ("domain", "public", "private"): - raise ValueError("Incorrect profile: {}".format(profile)) + raise ValueError(f"Incorrect profile: {profile}") if section.lower() not in ("state", "firewallpolicy", "settings", "logging"): - raise ValueError("Incorrect section: {}".format(section)) + raise ValueError(f"Incorrect section: {section}") if store.lower() not in ("local", "lgpo"): - raise ValueError("Incorrect store: {}".format(store)) - command = "show {}profile {}".format(profile, section) + raise ValueError(f"Incorrect store: {store}") + command = f"show {profile}profile {section}" # run it results = _netsh_command(command=command, store=store) # sample output: @@ -209,7 +197,7 @@ def get_settings(profile, section, store="local"): # if it's less than 3 lines it failed if len(results) < 3: - raise CommandExecutionError("Invalid results: {}".format(results)) + raise CommandExecutionError(f"Invalid results: {results}") ret = {} # Skip the first 2 lines. Add everything else to a dictionary for line in results[3:]: @@ -339,20 +327,20 @@ def set_firewall_settings(profile, inbound=None, outbound=None, store="local"): """ # Input validation if profile.lower() not in ("domain", "public", "private"): - raise ValueError("Incorrect profile: {}".format(profile)) + raise ValueError(f"Incorrect profile: {profile}") if inbound and inbound.lower() not in ( "blockinbound", "blockinboundalways", "allowinbound", "notconfigured", ): - raise ValueError("Incorrect inbound value: {}".format(inbound)) + raise ValueError(f"Incorrect inbound value: {inbound}") if outbound and outbound.lower() not in ( "allowoutbound", "blockoutbound", "notconfigured", ): - raise ValueError("Incorrect outbound value: {}".format(outbound)) + raise ValueError(f"Incorrect outbound value: {outbound}") if not inbound and not outbound: raise ValueError("Must set inbound or outbound") @@ -366,12 +354,12 @@ def set_firewall_settings(profile, inbound=None, outbound=None, store="local"): if not outbound: outbound = ret["Outbound"] - command = "set {}profile firewallpolicy {},{}".format(profile, inbound, outbound) + command = f"set {profile}profile firewallpolicy {inbound},{outbound}" results = _netsh_command(command=command, store=store) if results: - raise CommandExecutionError("An error occurred: {}".format(results)) + raise CommandExecutionError(f"An error occurred: {results}") return True @@ -441,17 +429,17 @@ def set_logging_settings(profile, setting, value, store="local"): """ # Input validation if profile.lower() not in ("domain", "public", "private"): - raise ValueError("Incorrect profile: {}".format(profile)) + raise ValueError(f"Incorrect profile: {profile}") if setting.lower() not in ( "allowedconnections", "droppedconnections", "filename", "maxfilesize", ): - raise ValueError("Incorrect setting: {}".format(setting)) + raise ValueError(f"Incorrect setting: {setting}") if setting.lower() in ("allowedconnections", "droppedconnections"): if value.lower() not in ("enable", "disable", "notconfigured"): - raise ValueError("Incorrect value: {}".format(value)) + raise ValueError(f"Incorrect value: {value}") # TODO: Consider adding something like the following to validate filename # https://stackoverflow.com/questions/9532499/check-whether-a-path-is-valid-in-python-without-creating-a-file-at-the-paths-ta if setting.lower() == "maxfilesize": @@ -460,16 +448,16 @@ def set_logging_settings(profile, setting, value, store="local"): try: int(value) except ValueError: - raise ValueError("Incorrect value: {}".format(value)) + raise ValueError(f"Incorrect value: {value}") if not 1 <= int(value) <= 32767: - raise ValueError("Incorrect value: {}".format(value)) + raise ValueError(f"Incorrect value: {value}") # Run the command - command = "set {}profile logging {} {}".format(profile, setting, value) + command = f"set {profile}profile logging {setting} {value}" results = _netsh_command(command=command, store=store) # A successful run should return an empty list if results: - raise CommandExecutionError("An error occurred: {}".format(results)) + raise CommandExecutionError(f"An error occurred: {results}") return True @@ -521,7 +509,7 @@ def set_settings(profile, setting, value, store="local"): """ # Input validation if profile.lower() not in ("domain", "public", "private"): - raise ValueError("Incorrect profile: {}".format(profile)) + raise ValueError(f"Incorrect profile: {profile}") if setting.lower() not in ( "localfirewallrules", "localconsecrules", @@ -529,17 +517,17 @@ def set_settings(profile, setting, value, store="local"): "remotemanagement", "unicastresponsetomulticast", ): - raise ValueError("Incorrect setting: {}".format(setting)) + raise ValueError(f"Incorrect setting: {setting}") if value.lower() not in ("enable", "disable", "notconfigured"): - raise ValueError("Incorrect value: {}".format(value)) + raise ValueError(f"Incorrect value: {value}") # Run the command - command = "set {}profile settings {} {}".format(profile, setting, value) + command = f"set {profile}profile settings {setting} {value}" results = _netsh_command(command=command, store=store) # A successful run should return an empty list if results: - raise CommandExecutionError("An error occurred: {}".format(results)) + raise CommandExecutionError(f"An error occurred: {results}") return True @@ -582,16 +570,16 @@ def set_state(profile, state, store="local"): """ # Input validation if profile.lower() not in ("domain", "public", "private"): - raise ValueError("Incorrect profile: {}".format(profile)) + raise ValueError(f"Incorrect profile: {profile}") if state.lower() not in ("on", "off", "notconfigured"): - raise ValueError("Incorrect state: {}".format(state)) + raise ValueError(f"Incorrect state: {state}") # Run the command - command = "set {}profile state {}".format(profile, state) + command = f"set {profile}profile state {state}" results = _netsh_command(command=command, store=store) # A successful run should return an empty list if results: - raise CommandExecutionError("An error occurred: {}".format(results)) + raise CommandExecutionError(f"An error occurred: {results}") return True diff --git a/salt/utils/win_lgpo_reg.py b/salt/utils/win_lgpo_reg.py index 8e3af61b858c..bbd5dffdbff9 100644 --- a/salt/utils/win_lgpo_reg.py +++ b/salt/utils/win_lgpo_reg.py @@ -47,18 +47,6 @@ log = logging.getLogger(__name__) -__virtualname__ = "lgpo_reg" - - -def __virtual__(): - """ - Only works on Windows with the lgpo_reg module - """ - if not salt.utils.platform.is_windows(): - return False, "LGPO_REG Util: Only available on Windows" - - return __virtualname__ - def search_reg_pol(search_string, policy_data): """ diff --git a/salt/utils/win_network.py b/salt/utils/win_network.py index 0f0549154a0b..fe93636cbea9 100644 --- a/salt/utils/win_network.py +++ b/salt/utils/win_network.py @@ -20,16 +20,12 @@ """ # https://docs.microsoft.com/en-us/dotnet/api/system.net.networkinformation.networkinterface.getallnetworkinterfaces?view=netframework-4.7.2 -import platform +import sys import salt.utils.win_reg from salt._compat import ipaddress -IS_WINDOWS = platform.system() == "Windows" - -__virtualname__ = "win_network" - -if IS_WINDOWS: +if sys.platform.startswith("win"): # pythonnet 3.0.1 requires .NET 4.7.2 (461808). This isn't installed by # default until Windows Server 2019 / Windows 10 1809 (10.1.17763). But, it # can be installed on older versions of Windows. So, instead of checking @@ -114,16 +110,6 @@ af_inet6 = 23 -def __virtual__(): - """ - Only load if windows - """ - if not IS_WINDOWS: - return False, "This utility will only run on Windows" - - return __virtualname__ - - def _get_base_properties(i_face): raw_mac = i_face.GetPhysicalAddress().ToString() try: diff --git a/salt/utils/win_osinfo.py b/salt/utils/win_osinfo.py index 56f1e12d50ff..d3d0e061e78d 100644 --- a/salt/utils/win_osinfo.py +++ b/salt/utils/win_osinfo.py @@ -21,18 +21,6 @@ ) -# Although utils are often directly imported, it is also possible to use the -# loader. -def __virtual__(): - """ - Only load if Win32 Libraries are installed - """ - if not HAS_WIN32: - return False, "This utility requires pywin32" - - return "win_osinfo" - - def os_version_info_ex(): """ Helper function to return the results of the GetVersionExW Windows API call. diff --git a/salt/utils/win_pdh.py b/salt/utils/win_pdh.py index fcd395184a4d..bf8a154c4a53 100644 --- a/salt/utils/win_pdh.py +++ b/salt/utils/win_pdh.py @@ -38,7 +38,6 @@ import logging import time -import salt.utils.platform from salt.exceptions import CommandExecutionError try: @@ -52,22 +51,6 @@ log = logging.getLogger(__file__) -# Define the virtual name -__virtualname__ = "pdh" - - -def __virtual__(): - """ - Only works on Windows systems with the PyWin32 - """ - if not salt.utils.platform.is_windows(): - return False, "salt.utils.win_pdh: Requires Windows" - - if not HAS_WINDOWS_MODULES: - return False, "salt.utils.win_pdh: Missing required modules" - - return __virtualname__ - class Counter: """ @@ -167,7 +150,7 @@ def build_counter(obj, instance, instance_index, counter): ) if win32pdh.ValidatePath(path) == 0: return Counter(path, obj, instance, instance_index, counter) - raise CommandExecutionError("Invalid counter specified: {}".format(path)) + raise CommandExecutionError(f"Invalid counter specified: {path}") build_counter = staticmethod(build_counter) diff --git a/salt/utils/win_reg.py b/salt/utils/win_reg.py index 74aa17b5d811..454df4b83cda 100644 --- a/salt/utils/win_reg.py +++ b/salt/utils/win_reg.py @@ -25,8 +25,6 @@ :depends: - PyWin32 """ -# When production windows installer is using Python 3, Python 2 code can be removed - import logging import salt.utils.platform @@ -45,31 +43,6 @@ log = logging.getLogger(__name__) -# Define the module's virtual name -__virtualname__ = "reg" - - -def __virtual__(): - """ - Only works on Windows systems with the PyWin32 - """ - if not salt.utils.platform.is_windows(): - return ( - False, - "reg execution module failed to load: " - "The module will only run on Windows systems", - ) - - if not HAS_WINDOWS_MODULES: - return ( - False, - "reg execution module failed to load: " - "One of the following libraries did not load: " - "win32gui, win32con, win32api", - ) - - return __virtualname__ - def _to_mbcs(vdata): """ @@ -186,7 +159,7 @@ def key_exists(hive, key, use_32bit_registry=False): try: hkey = registry.hkeys[local_hive] except KeyError: - raise CommandExecutionError("Invalid Hive: {}".format(local_hive)) + raise CommandExecutionError(f"Invalid Hive: {local_hive}") access_mask = registry.registry_32[use_32bit_registry] handle = None @@ -241,7 +214,7 @@ def value_exists(hive, key, vname, use_32bit_registry=False): try: hkey = registry.hkeys[local_hive] except KeyError: - raise CommandExecutionError("Invalid Hive: {}".format(local_hive)) + raise CommandExecutionError(f"Invalid Hive: {local_hive}") access_mask = registry.registry_32[use_32bit_registry] try: @@ -340,7 +313,7 @@ def list_keys(hive, key=None, use_32bit_registry=False): try: hkey = registry.hkeys[local_hive] except KeyError: - raise CommandExecutionError("Invalid Hive: {}".format(local_hive)) + raise CommandExecutionError(f"Invalid Hive: {local_hive}") access_mask = registry.registry_32[use_32bit_registry] subkeys = [] @@ -355,10 +328,10 @@ def list_keys(hive, key=None, use_32bit_registry=False): except win32api.error as exc: if exc.winerror == 2: log.debug(r"Cannot find key: %s\%s", hive, key, exc_info=True) - return False, r"Cannot find key: {}\{}".format(hive, key) + return False, rf"Cannot find key: {hive}\{key}" if exc.winerror == 5: log.debug(r"Access is denied: %s\%s", hive, key, exc_info=True) - return False, r"Access is denied: {}\{}".format(hive, key) + return False, rf"Access is denied: {hive}\{key}" raise finally: @@ -412,7 +385,7 @@ def list_values(hive, key=None, use_32bit_registry=False): try: hkey = registry.hkeys[local_hive] except KeyError: - raise CommandExecutionError("Invalid Hive: {}".format(local_hive)) + raise CommandExecutionError(f"Invalid Hive: {local_hive}") access_mask = registry.registry_32[use_32bit_registry] handle = None values = list() @@ -445,10 +418,10 @@ def list_values(hive, key=None, use_32bit_registry=False): except win32api.error as exc: if exc.winerror == 2: log.debug(r"Cannot find key: %s\%s", hive, key) - return False, r"Cannot find key: {}\{}".format(hive, key) + return False, rf"Cannot find key: {hive}\{key}" elif exc.winerror == 5: log.debug(r"Access is denied: %s\%s", hive, key) - return False, r"Access is denied: {}\{}".format(hive, key) + return False, rf"Access is denied: {hive}\{key}" raise finally: @@ -538,7 +511,7 @@ def read_value(hive, key, vname=None, use_32bit_registry=False): try: hkey = registry.hkeys[local_hive] except KeyError: - raise CommandExecutionError("Invalid Hive: {}".format(local_hive)) + raise CommandExecutionError(f"Invalid Hive: {local_hive}") access_mask = registry.registry_32[use_32bit_registry] handle = None @@ -574,13 +547,13 @@ def read_value(hive, key, vname=None, use_32bit_registry=False): raise except win32api.error as exc: if exc.winerror == 2: - msg = "Cannot find key: {}\\{}".format(local_hive, local_key) + msg = f"Cannot find key: {local_hive}\\{local_key}" log.trace(exc) log.trace(msg) ret["comment"] = msg ret["success"] = False elif exc.winerror == 5: - msg = "Access is denied: {}\\{}".format(local_hive, local_key) + msg = f"Access is denied: {local_hive}\\{local_key}" log.trace(exc) log.trace(msg) ret["comment"] = msg @@ -733,7 +706,7 @@ def set_value( try: hkey = registry.hkeys[local_hive] except KeyError: - raise CommandExecutionError("Invalid Hive: {}".format(local_hive)) + raise CommandExecutionError(f"Invalid Hive: {local_hive}") vtype_value = registry.vtype[local_vtype] access_mask = registry.registry_32[use_32bit_registry] | win32con.KEY_ALL_ACCESS @@ -886,7 +859,7 @@ def delete_key_recursive(hive, key, use_32bit_registry=False): try: hkey = registry.hkeys[local_hive] except KeyError: - raise CommandExecutionError("Invalid Hive: {}".format(local_hive)) + raise CommandExecutionError(f"Invalid Hive: {local_hive}") key_path = local_key access_mask = registry.registry_32[use_32bit_registry] | win32con.KEY_ALL_ACCESS @@ -918,7 +891,7 @@ def _traverse_registry_tree(_hkey, _keypath, _ret, _access_mask): """ _key = win32api.RegOpenKeyEx(_hkey, _keypath, 0, _access_mask) for subkeyname in _subkeys(_key): - subkeypath = "{}\\{}".format(_keypath, subkeyname) + subkeypath = f"{_keypath}\\{subkeyname}" _ret = _traverse_registry_tree(_hkey, subkeypath, _ret, access_mask) _ret.append(subkeypath) return _ret @@ -938,13 +911,13 @@ def _traverse_registry_tree(_hkey, _keypath, _ret, _access_mask): key_handle = win32api.RegOpenKeyEx(hkey, sub_key_path, 0, access_mask) try: win32api.RegDeleteKey(key_handle, "") - ret["Deleted"].append(r"{}\{}".format(hive, sub_key_path)) + ret["Deleted"].append(rf"{hive}\{sub_key_path}") except OSError as exc: log.error(exc, exc_info=True) - ret["Failed"].append(r"{}\{} {}".format(hive, sub_key_path, exc)) + ret["Failed"].append(rf"{hive}\{sub_key_path} {exc}") except win32api.error as exc: log.error(exc, exc_info=True) - ret["Failed"].append(r"{}\{} {}".format(hive, sub_key_path, exc.strerror)) + ret["Failed"].append(rf"{hive}\{sub_key_path} {exc.strerror}") finally: if key_handle: win32api.RegCloseKey(key_handle) @@ -998,7 +971,7 @@ def delete_value(hive, key, vname=None, use_32bit_registry=False): try: hkey = registry.hkeys[local_hive] except KeyError: - raise CommandExecutionError("Invalid Hive: {}".format(local_hive)) + raise CommandExecutionError(f"Invalid Hive: {local_hive}") access_mask = registry.registry_32[use_32bit_registry] | win32con.KEY_ALL_ACCESS handle = None diff --git a/salt/utils/win_runas.py b/salt/utils/win_runas.py index 0b695aaad268..3bbb5a568aad 100644 --- a/salt/utils/win_runas.py +++ b/salt/utils/win_runas.py @@ -39,18 +39,6 @@ log = logging.getLogger(__name__) -# Although utils are often directly imported, it is also possible to use the -# loader. -def __virtual__(): - """ - Only load if Win32 Libraries are installed - """ - if not HAS_WIN32 or not HAS_PSUTIL: - return False, "This utility requires pywin32 and psutil" - - return "win_runas" - - def split_username(username): domain = "." user_name = username diff --git a/salt/utils/win_service.py b/salt/utils/win_service.py index c05652c65c5c..e56117af29a3 100644 --- a/salt/utils/win_service.py +++ b/salt/utils/win_service.py @@ -1,4 +1,3 @@ -import salt.utils.platform from salt.exceptions import CommandExecutionError try: @@ -76,21 +75,6 @@ "critical": 3, } -__virtualname__ = "win_service" - - -def __virtual__(): - """ - Only load if Win32 Libraries are installed - """ - if not salt.utils.platform.is_windows(): - return False, "win_dacl: Requires Windows" - - if not HAS_WIN32: - return False, "win_dacl: Requires pywin32" - - return __virtualname__ - def info(name): """ @@ -114,9 +98,7 @@ def info(name): None, None, win32service.SC_MANAGER_CONNECT ) except pywintypes.error as exc: - raise CommandExecutionError( - "Failed to connect to the SCM: {}".format(exc.strerror) - ) + raise CommandExecutionError(f"Failed to connect to the SCM: {exc.strerror}") try: handle_svc = win32service.OpenService( @@ -128,7 +110,7 @@ def info(name): | win32service.SERVICE_QUERY_STATUS, ) except pywintypes.error as exc: - raise CommandExecutionError("Failed To Open {}: {}".format(name, exc.strerror)) + raise CommandExecutionError(f"Failed To Open {name}: {exc.strerror}") try: config_info = win32service.QueryServiceConfig(handle_svc) @@ -150,7 +132,7 @@ def info(name): ret = dict() try: - sid = win32security.LookupAccountName("", "NT Service\\{}".format(name))[0] + sid = win32security.LookupAccountName("", f"NT Service\\{name}")[0] ret["sid"] = win32security.ConvertSidToStringSid(sid) except pywintypes.error: ret["sid"] = "Failed to get SID" diff --git a/salt/utils/win_system.py b/salt/utils/win_system.py index e9f38c9171eb..7c95a7c44523 100644 --- a/salt/utils/win_system.py +++ b/salt/utils/win_system.py @@ -24,31 +24,10 @@ log = logging.getLogger(__name__) -# Define the module's virtual name -__virtualname__ = "win_system" MINION_VOLATILE_KEY = "SYSTEM\\CurrentControlSet\\Services\\salt-minion\\Volatile-Data" REBOOT_REQUIRED_NAME = "Reboot required" -def __virtual__(): - """ - Only works on Windows systems - """ - if not salt.utils.platform.is_windows(): - return ( - False, - "win_system salt util failed to load: " - "The util will only run on Windows systems", - ) - if not HAS_WIN32_MODS: - return ( - False, - "win_system salt util failed to load: " - "The util will only run on Windows systems", - ) - return __virtualname__ - - def get_computer_name(): """ Get the Windows computer name. Uses the win32api to get the current computer diff --git a/salt/utils/win_update.py b/salt/utils/win_update.py index 778acd141fa1..8cf982d414bf 100644 --- a/salt/utils/win_update.py +++ b/salt/utils/win_update.py @@ -25,16 +25,6 @@ 2: "Can Require Reboot", } -__virtualname__ = "win_update" - - -def __virtual__(): - if not salt.utils.platform.is_windows(): - return False, "win_update: Only available on Windows" - if not HAS_PYWIN32: - return False, "win_update: Missing pywin32" - return __virtualname__ - class Updates: """ @@ -398,14 +388,14 @@ def refresh(self, online=True): results = searcher.Search(search_string) if results.Updates.Count == 0: log.debug("No Updates found for:\n\t\t%s", search_string) - return "No Updates found: {}".format(search_string) + return f"No Updates found: {search_string}" except pywintypes.com_error as error: # Something happened, raise an error hr, msg, exc, arg = error.args # pylint: disable=W0633 try: failure_code = self.fail_codes[exc[5]] except KeyError: - failure_code = "Unknown Failure: {}".format(error) + failure_code = f"Unknown Failure: {error}" log.error("Search Failed: %s\n\t\t%s", failure_code, search_string) raise CommandExecutionError(failure_code) @@ -719,7 +709,7 @@ def download(self, updates): try: failure_code = self.fail_codes[exc[5]] except KeyError: - failure_code = "Unknown Failure: {}".format(error) + failure_code = f"Unknown Failure: {error}" log.error("Download Failed: %s", failure_code) raise CommandExecutionError(failure_code) @@ -828,7 +818,7 @@ def install(self, updates): try: failure_code = self.fail_codes[exc[5]] except KeyError: - failure_code = "Unknown Failure: {}".format(error) + failure_code = f"Unknown Failure: {error}" log.error("Install Failed: %s", failure_code) raise CommandExecutionError(failure_code) @@ -962,7 +952,7 @@ def uninstall(self, updates): try: failure_code = self.fail_codes[exc[5]] except KeyError: - failure_code = "Unknown Failure: {}".format(error) + failure_code = f"Unknown Failure: {error}" # If "Uninstall Not Allowed" error, try using DISM if exc[5] == -2145124312: @@ -992,7 +982,7 @@ def uninstall(self, updates): "dism", "/Online", "/Remove-Package", - "/PackageName:{}".format(pkg), + f"/PackageName:{pkg}", "/Quiet", "/NoRestart", ] @@ -1004,7 +994,7 @@ def uninstall(self, updates): log.debug("Command: %s", " ".join(cmd)) log.debug("Error: %s", exc) raise CommandExecutionError( - "Uninstall using DISM failed: {}".format(exc) + f"Uninstall using DISM failed: {exc}" ) # DISM Uninstall Completed Successfully diff --git a/salt/utils/winapi.py b/salt/utils/winapi.py index 38d9a032c2c3..5a9ea97f5667 100644 --- a/salt/utils/winapi.py +++ b/salt/utils/winapi.py @@ -11,16 +11,6 @@ log = logging.getLogger(__name__) -def __virtual__(): - """ - Only load if required libraries exist - """ - if not HAS_LIBS: - return False - else: - return True - - class Com: def __init__(self): self.need_com_init = not self._is_main_thread() diff --git a/tests/pytests/functional/modules/win_file/test_check_perms.py b/tests/pytests/functional/modules/win_file/test_check_perms.py index 53e656eab18d..df1adec85bec 100644 --- a/tests/pytests/functional/modules/win_file/test_check_perms.py +++ b/tests/pytests/functional/modules/win_file/test_check_perms.py @@ -16,15 +16,7 @@ @pytest.fixture def configure_loader_modules(): - return { - win_file: { - "__utils__": { - "dacl.check_perms": win_dacl.check_perms, - "dacl.set_perms": win_dacl.set_perms, - } - }, - win_dacl: {"__opts__": {"test": False}}, - } + return {win_file: {}} @pytest.fixture(scope="function") @@ -43,7 +35,7 @@ def test_check_perms_set_owner_test_true(test_file): "name": str(test_file), "result": None, } - with patch.dict(win_dacl.__opts__, {"test": True}): + with patch.dict(win_file.__opts__, {"test": True}): result = win_file.check_perms( path=str(test_file), owner="Backup Operators", inheritance=None ) @@ -76,7 +68,7 @@ def test_check_perms_deny_test_true(test_file): "name": str(test_file), "result": None, } - with patch.dict(win_dacl.__opts__, {"test": True}): + with patch.dict(win_file.__opts__, {"test": True}): result = win_file.check_perms( path=str(test_file), deny_perms={"Users": {"perms": "read_execute"}}, @@ -113,7 +105,7 @@ def test_check_perms_grant_test_true(test_file): "name": str(test_file), "result": None, } - with patch.dict(win_dacl.__opts__, {"test": True}): + with patch.dict(win_file.__opts__, {"test": True}): result = win_file.check_perms( path=str(test_file), grant_perms={"Users": {"perms": "read_execute"}}, @@ -150,7 +142,7 @@ def test_check_perms_inheritance_false_test_true(test_file): "name": str(test_file), "result": None, } - with patch.dict(win_dacl.__opts__, {"test": True}): + with patch.dict(win_file.__opts__, {"test": True}): result = win_file.check_perms(path=str(test_file), inheritance=False) assert result == expected @@ -214,7 +206,7 @@ def test_check_perms_reset_test_true(test_file): "name": str(test_file), "result": None, } - with patch.dict(win_dacl.__opts__, {"test": True}): + with patch.dict(win_file.__opts__, {"test": True}): result = win_file.check_perms( path=str(test_file), grant_perms={ diff --git a/tests/pytests/functional/utils/win_dacl/test_file.py b/tests/pytests/functional/utils/win_dacl/test_file.py index bb6bd1238696..7de08f034225 100644 --- a/tests/pytests/functional/utils/win_dacl/test_file.py +++ b/tests/pytests/functional/utils/win_dacl/test_file.py @@ -1,7 +1,6 @@ import pytest import salt.utils.win_dacl as win_dacl -from tests.support.mock import patch pytestmark = [ pytest.mark.windows_whitelisted, @@ -819,22 +818,22 @@ def test_check_perms(test_file): def test_check_perms_test_true(test_file): - with patch.dict(win_dacl.__opts__, {"test": True}): - result = win_dacl.check_perms( - obj_name=str(test_file), - obj_type="file", - ret=None, - owner="Users", - grant_perms={"Backup Operators": {"perms": "read"}}, - deny_perms={ - "NETWORK SERVICE": { - "perms": ["delete", "set_value", "write_dac", "write_owner"] - }, - "Backup Operators": {"perms": ["delete"]}, + result = win_dacl.check_perms( + obj_name=str(test_file), + obj_type="file", + ret=None, + owner="Users", + grant_perms={"Backup Operators": {"perms": "read"}}, + deny_perms={ + "NETWORK SERVICE": { + "perms": ["delete", "set_value", "write_dac", "write_owner"] }, - inheritance=True, - reset=False, - ) + "Backup Operators": {"perms": ["delete"]}, + }, + inheritance=True, + reset=False, + test_mode=True, + ) expected = { "changes": { diff --git a/tests/pytests/functional/utils/win_dacl/test_reg.py b/tests/pytests/functional/utils/win_dacl/test_reg.py index af6de169e6c3..e296b4f0dffd 100644 --- a/tests/pytests/functional/utils/win_dacl/test_reg.py +++ b/tests/pytests/functional/utils/win_dacl/test_reg.py @@ -3,7 +3,6 @@ import salt.utils.win_dacl as win_dacl import salt.utils.win_reg as win_reg -from tests.support.mock import patch pytestmark = [ pytest.mark.windows_whitelisted, @@ -29,7 +28,7 @@ def fake_key(): @pytest.fixture(scope="function") def reg_key(fake_key): win_reg.set_value(hive="HKLM", key=fake_key, vname="fake_name", vdata="fake_data") - yield "HKLM\\{}".format(fake_key) + yield f"HKLM\\{fake_key}" win_reg.delete_key_recursive(hive="HKLM", key=fake_key) @@ -433,22 +432,22 @@ def test_check_perms(reg_key): def test_check_perms_test_true(reg_key): - with patch.dict(win_dacl.__opts__, {"test": True}): - result = win_dacl.check_perms( - obj_name=reg_key, - obj_type="registry", - ret=None, - owner="Users", - grant_perms={"Backup Operators": {"perms": "read"}}, - deny_perms={ - "NETWORK SERVICE": { - "perms": ["delete", "set_value", "write_dac", "write_owner"] - }, - "Backup Operators": {"perms": ["delete"]}, + result = win_dacl.check_perms( + obj_name=reg_key, + obj_type="registry", + ret=None, + owner="Users", + grant_perms={"Backup Operators": {"perms": "read"}}, + deny_perms={ + "NETWORK SERVICE": { + "perms": ["delete", "set_value", "write_dac", "write_owner"] }, - inheritance=True, - reset=False, - ) + "Backup Operators": {"perms": ["delete"]}, + }, + inheritance=True, + reset=False, + test_mode=True, + ) expected = { "changes": { diff --git a/tests/pytests/unit/modules/test_win_path.py b/tests/pytests/unit/modules/test_win_path.py index 7dad024a8783..670e09c5119a 100644 --- a/tests/pytests/unit/modules/test_win_path.py +++ b/tests/pytests/unit/modules/test_win_path.py @@ -1,22 +1,19 @@ """ +Test cases for salt.modules.win_path. + :codeauthor: Rahul Handay """ - - import os import pytest import salt.modules.win_path as win_path -import salt.utils.stringutils -import salt.utils.win_reg as reg_util from tests.support.mock import MagicMock, patch -pytestmark = [pytest.mark.windows_whitelisted, pytest.mark.skip_unless_on_windows] - -""" -Test cases for salt.modules.win_path. -""" +pytestmark = [ + pytest.mark.windows_whitelisted, + pytest.mark.skip_unless_on_windows, +] @pytest.fixture() @@ -26,13 +23,7 @@ def pathsep(): @pytest.fixture def configure_loader_modules(): - return { - win_path: { - "__opts__": {"test": False}, - "__salt__": {}, - "__utils__": {"reg.read_value": reg_util.read_value}, - }, - } + return {win_path: {}} def test_get_path(): @@ -40,7 +31,7 @@ def test_get_path(): Test to return the system path """ mock = MagicMock(return_value={"vdata": "C:\\Salt"}) - with patch.dict(win_path.__utils__, {"reg.read_value": mock}): + with patch("salt.utils.win_reg.read_value", mock): assert win_path.get_path() == ["C:\\Salt"] @@ -61,7 +52,7 @@ def test_util_reg(): Test to check if registry comes back clean when get_path is called """ mock = MagicMock(return_value={"vdata": ""}) - with patch.dict(win_path.__utils__, {"reg.read_value": mock}): + with patch("salt.utils.win_reg.read_value", mock): assert win_path.get_path() == [] @@ -73,7 +64,7 @@ def test_add(pathsep): # Helper function to make the env var easier to reuse def _env(path): - return {"PATH": salt.utils.stringutils.to_str(pathsep.join(path))} + return {"PATH": pathsep.join(path)} # Helper function to make the run call easier to reuse def _run(name, index=None, retval=True, path=None): @@ -85,17 +76,17 @@ def _run(name, index=None, retval=True, path=None): mock_set = MagicMock(return_value=retval) # Mock individual calls that would occur during normal usage - patch_sep = patch.object(win_path, "PATHSEP", pathsep) + patch_sep = patch("salt.modules.win_path.os.pathsep", pathsep) patch_path = patch.object(win_path, "get_path", mock_get) patch_env = patch.object(os, "environ", env) - patch_dict = patch.dict(win_path.__utils__, {"reg.set_value": mock_set}) + patch_win_reg = patch("salt.utils.win_reg.set_value", mock_set) patch_rehash = patch.object(win_path, "rehash", MagicMock(return_value=True)) - with patch_sep, patch_path, patch_env, patch_dict, patch_rehash: + with patch_sep, patch_path, patch_env, patch_win_reg, patch_rehash: return win_path.add(name, index), env, mock_set def _path_matches(path): - return salt.utils.stringutils.to_str(pathsep.join(path)) + return pathsep.join(path) # Test an empty reg update ret, env, mock_set = _run("") @@ -191,7 +182,7 @@ def test_remove(pathsep): # Helper function to make the env var easier to reuse def _env(path): - return {"PATH": salt.utils.stringutils.to_str(pathsep.join(path))} + return {"PATH": pathsep.join(path)} def _run(name="c:\\salt", retval=True, path=None): if path is None: @@ -201,16 +192,16 @@ def _run(name="c:\\salt", retval=True, path=None): mock_get = MagicMock(return_value=list(path)) mock_set = MagicMock(return_value=retval) - patch_path_sep = patch.object(win_path, "PATHSEP", pathsep) + patch_path_sep = patch("salt.modules.win_path.os.pathsep", pathsep) patch_path = patch.object(win_path, "get_path", mock_get) patch_env = patch.object(os, "environ", env) - patch_dict = patch.dict(win_path.__utils__, {"reg.set_value": mock_set}) + patch_win_reg = patch("salt.utils.win_reg.set_value", mock_set) patch_rehash = patch.object(win_path, "rehash", MagicMock(return_value=True)) - with patch_path_sep, patch_path, patch_env, patch_dict, patch_rehash: + with patch_path_sep, patch_path, patch_env, patch_win_reg, patch_rehash: return win_path.remove(name), env, mock_set def _path_matches(path): - return salt.utils.stringutils.to_str(pathsep.join(path)) + return pathsep.join(path) # Test a successful reg update ret, env, mock_set = _run("C:\\Bar", retval=True) diff --git a/tests/pytests/unit/states/test_environ.py b/tests/pytests/unit/states/test_environ.py index 7347f7dbe171..658a0f8bcf00 100644 --- a/tests/pytests/unit/states/test_environ.py +++ b/tests/pytests/unit/states/test_environ.py @@ -39,25 +39,18 @@ def test_setenv_permanent(): """ test that we can set permanent environment variables (requires pywin32) """ - with patch.dict( - envmodule.__utils__, - { - "reg.set_value": MagicMock(), - "reg.delete_value": MagicMock(), - "win_functions.broadcast_setting_change": MagicMock(), - }, + with patch("salt.utils.win_reg.set_value", MagicMock()) as set_value, patch( + "salt.utils.win_reg.delete_value", MagicMock() + ) as delete_value, patch( + "salt.utils.win_functions.broadcast_setting_change", MagicMock() ): ret = envstate.setenv("test", "value", permanent=True) assert ret["changes"] == {"test": "value"} - envmodule.__utils__["reg.set_value"].assert_called_with( - "HKCU", "Environment", "test", "value" - ) + set_value.assert_called_with("HKCU", "Environment", "test", "value") ret = envstate.setenv("test", False, false_unsets=True, permanent=True) assert ret["changes"] == {"test": None} - envmodule.__utils__["reg.delete_value"].assert_called_with( - "HKCU", "Environment", "test" - ) + delete_value.assert_called_with("HKCU", "Environment", "test") def test_setenv_dict(): @@ -125,7 +118,7 @@ def test_setenv_unset_multi(): ret = envstate.setenv("notimportant", {"foo": "bar"}) assert ret["changes"] == {"foo": "bar"} - with patch.dict(envstate.__utils__, {"reg.read_value": MagicMock()}): + with patch("salt.utils.win_reg.read_value", MagicMock()): ret = envstate.setenv( "notimportant", {"test": False, "foo": "baz"}, false_unsets=True ) @@ -135,7 +128,7 @@ def test_setenv_unset_multi(): else: assert envstate.os.environ == {"INITIAL": "initial", "foo": "baz"} - with patch.dict(envstate.__utils__, {"reg.read_value": MagicMock()}): + with patch("salt.utils.win_reg.read_value", MagicMock()): ret = envstate.setenv("notimportant", {"test": False, "foo": "bax"}) assert ret["changes"] == {"test": "", "foo": "bax"} if salt.utils.platform.is_windows(): diff --git a/tests/pytests/unit/utils/win_lgpo/test_netsh.py b/tests/pytests/unit/utils/win_lgpo/test_netsh.py index e77b64fd61a9..d1d49652fe13 100644 --- a/tests/pytests/unit/utils/win_lgpo/test_netsh.py +++ b/tests/pytests/unit/utils/win_lgpo/test_netsh.py @@ -30,7 +30,7 @@ def test_get_settings_firewallpolicy_lgpo_issue_57591(): """ Should not stacktrace when the hostname contains unicode characters """ - with patch.object(win_lgpo_netsh, "__hostname__", return_value="kомпьютер"): + with patch("salt.utils.win_lgpo_netsh._hostname", return_value="kомпьютер"): ret = win_lgpo_netsh.get_settings( profile="domain", section="firewallpolicy", store="lgpo" )