Best Python code snippet using fMBT_python
win_psget.py
Source:win_psget.py
1# -*- coding: utf-8 -*-2"""3Module for managing PowerShell through PowerShellGet (PSGet)4:depends:5 - PowerShell 5.06 - PSGet7Support for PowerShell8"""9from __future__ import absolute_import, print_function, unicode_literals10# Import Python libs11import logging12import xml.etree.ElementTree13# Import Salt libs14import salt.utils.platform15import salt.utils.versions16from salt.exceptions import CommandExecutionError17# Set up logging18log = logging.getLogger(__name__)19# Define the module's virtual name20__virtualname__ = "psget"21def __virtual__():22 """23 Set the system module of the kernel is Windows24 """25 # Verify Windows26 if not salt.utils.platform.is_windows():27 log.debug("Module PSGet: Only available on Windows systems")28 return False, "Module PSGet: Only available on Windows systems"29 # Verify PowerShell30 powershell_info = __salt__["cmd.shell_info"]("powershell")31 if not powershell_info["installed"]:32 log.debug("Module PSGet: Requires PowerShell")33 return False, "Module PSGet: Requires PowerShell"34 # Verify PowerShell 5.0 or greater35 if salt.utils.versions.compare(powershell_info["version"], "<", "5.0"):36 log.debug("Module PSGet: Requires PowerShell 5 or newer")37 return False, "Module PSGet: Requires PowerShell 5 or newer."38 return __virtualname__39def _ps_xml_to_dict(parent, dic=None):40 """41 Formats powershell Xml to a dict.42 Note: This _ps_xml_to_dict is not perfect with powershell Xml.43 """44 if dic is None:45 dic = {}46 for child in parent:47 if list(child):48 new_dic = _ps_xml_to_dict(child, {})49 if "Name" in new_dic:50 dic[new_dic["Name"]] = new_dic51 else:52 try:53 dic[54 [name for ps_type, name in child.items() if ps_type == "Type"][55 056 ]57 ] = new_dic58 except IndexError:59 dic[child.text] = new_dic60 else:61 for xml_type, name in child.items():62 if xml_type == "Name":63 dic[name] = child.text64 return dic65def _pshell(cmd, cwd=None, depth=2):66 """67 Execute the desired powershell command and ensure that it returns data68 in Xml format and load that into python69 """70 cmd = '{0} | ConvertTo-Xml -Depth {1} -As "stream"'.format(cmd, depth)71 log.debug("DSC: %s", cmd)72 results = __salt__["cmd.run_all"](73 cmd, shell="powershell", cwd=cwd, python_shell=True74 )75 if "pid" in results:76 del results["pid"]77 if "retcode" not in results or results["retcode"] != 0:78 # run_all logs an error to log.error, fail hard back to the user79 raise CommandExecutionError(80 "Issue executing powershell {0}".format(cmd), info=results81 )82 try:83 ret = _ps_xml_to_dict(84 xml.etree.ElementTree.fromstring(results["stdout"].encode("utf-8"))85 )86 except xml.etree.ElementTree.ParseError:87 results["stdout"] = results["stdout"][:1000] + ". . ."88 raise CommandExecutionError("No XML results from powershell", info=results)89 return ret90def bootstrap():91 """92 Make sure that nuget-anycpu.exe is installed.93 This will download the official nuget-anycpu.exe from the internet.94 CLI Example:95 .. code-block:: bash96 salt 'win01' psget.bootstrap97 """98 cmd = "Get-PackageProvider -Name NuGet -ForceBootstrap | Select Name, Version, ProviderPath"99 ret = _pshell(cmd, depth=1)100 return ret101def avail_modules(desc=False):102 """103 List available modules in registered Powershell module repositories.104 :param desc: If ``True``, the verbose description will be returned.105 :type desc: ``bool``106 CLI Example:107 .. code-block:: bash108 salt 'win01' psget.avail_modules109 salt 'win01' psget.avail_modules desc=True110 """111 cmd = "Find-Module | Select Name, Description"112 modules = _pshell(cmd, depth=1)113 names = []114 if desc:115 names = {}116 for key in modules:117 module = modules[key]118 if desc:119 names[module["Name"]] = module["Description"]120 continue121 names.append(module["Name"])122 return names123def list_modules(desc=False):124 """125 List currently installed PSGet Modules on the system.126 :param desc: If ``True``, the verbose description will be returned.127 :type desc: ``bool``128 CLI Example:129 .. code-block:: bash130 salt 'win01' psget.list_modules131 salt 'win01' psget.list_modules desc=True132 """133 cmd = "Get-InstalledModule"134 modules = _pshell(cmd)135 names = []136 if desc:137 names = {}138 for key in modules:139 module = modules[key]140 if desc:141 names[module["Name"]] = module142 continue143 names.append(module["Name"])144 return names145def install(146 name, minimum_version=None, required_version=None, scope=None, repository=None147):148 """149 Install a Powershell module from powershell gallery on the system.150 :param name: Name of a Powershell module151 :type name: ``str``152 :param minimum_version: The maximum version to install, e.g. 1.23.2153 :type minimum_version: ``str``154 :param required_version: Install a specific version155 :type required_version: ``str``156 :param scope: The scope to install the module to, e.g. CurrentUser, Computer157 :type scope: ``str``158 :param repository: The friendly name of a private repository, e.g. MyREpo159 :type repository: ``str``160 CLI Example:161 .. code-block:: bash162 salt 'win01' psget.install PowerPlan163 """164 # Putting quotes around the parameter protects against command injection165 flags = [("Name", name)]166 if minimum_version is not None:167 flags.append(("MinimumVersion", minimum_version))168 if required_version is not None:169 flags.append(("RequiredVersion", required_version))170 if scope is not None:171 flags.append(("Scope", scope))172 if repository is not None:173 flags.append(("Repository", repository))174 params = ""175 for flag, value in flags:176 params += "-{0} {1} ".format(flag, value)177 cmd = "Install-Module {0} -Force".format(params)178 _pshell(cmd)179 return name in list_modules()180def update(name, maximum_version=None, required_version=None):181 """182 Update a PowerShell module to a specific version, or the newest183 :param name: Name of a Powershell module184 :type name: ``str``185 :param maximum_version: The maximum version to install, e.g. 1.23.2186 :type maximum_version: ``str``187 :param required_version: Install a specific version188 :type required_version: ``str``189 CLI Example:190 .. code-block:: bash191 salt 'win01' psget.update PowerPlan192 """193 # Putting quotes around the parameter protects against command injection194 flags = [("Name", name)]195 if maximum_version is not None:196 flags.append(("MaximumVersion", maximum_version))197 if required_version is not None:198 flags.append(("RequiredVersion", required_version))199 params = ""200 for flag, value in flags:201 params += "-{0} {1} ".format(flag, value)202 cmd = "Update-Module {0} -Force".format(params)203 _pshell(cmd)204 return name in list_modules()205def remove(name):206 """207 Remove a Powershell DSC module from the system.208 :param name: Name of a Powershell DSC module209 :type name: ``str``210 CLI Example:211 .. code-block:: bash212 salt 'win01' psget.remove PowerPlan213 """214 # Putting quotes around the parameter protects against command injection215 cmd = 'Uninstall-Module "{0}"'.format(name)216 no_ret = _pshell(cmd)217 return name not in list_modules()218def register_repository(name, location, installation_policy=None):219 """220 Register a PSGet repository on the local machine221 :param name: The name for the repository222 :type name: ``str``223 :param location: The URI for the repository224 :type location: ``str``225 :param installation_policy: The installation policy226 for packages, e.g. Trusted, Untrusted227 :type installation_policy: ``str``228 CLI Example:229 .. code-block:: bash230 salt 'win01' psget.register_repository MyRepo https://myrepo.mycompany.com/packages231 """232 # Putting quotes around the parameter protects against command injection233 flags = [("Name", name)]234 flags.append(("SourceLocation", location))235 if installation_policy is not None:236 flags.append(("InstallationPolicy", installation_policy))237 params = ""238 for flag, value in flags:239 params += "-{0} {1} ".format(flag, value)240 cmd = "Register-PSRepository {0}".format(params)241 no_ret = _pshell(cmd)242 return name not in list_modules()243def get_repository(name):244 """245 Get the details of a local PSGet repository246 :param name: Name of the repository247 :type name: ``str``248 CLI Example:249 .. code-block:: bash250 salt 'win01' psget.get_repository MyRepo251 """252 # Putting quotes around the parameter protects against command injection253 cmd = 'Get-PSRepository "{0}"'.format(name)254 no_ret = _pshell(cmd)...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!