How to use run_cmdlet method in lisa

Best Python code snippet using lisa_python

hyperv.py

Source:hyperv.py Github

copy

Full Screen

...16 @property17 def can_install(self) -> bool:18 return True19 def exists_vm(self, name: str) -> bool:20 output = self.node.tools[PowerShell].run_cmdlet(21 f"Get-VM -Name {name}",22 fail_on_error=False,23 force_run=True,24 )25 return output.strip() != ""26 def delete_vm(self, name: str) -> None:27 # check if vm is present28 if not self.exists_vm(name):29 return30 # stop and delete vm31 powershell = self.node.tools[PowerShell]32 powershell.run_cmdlet(33 f"Stop-VM -Name {name} -Force",34 force_run=True,35 )36 powershell.run_cmdlet(37 f"Remove-VM -Name {name} -Force",38 force_run=True,39 )40 def create_vm(41 self,42 name: str,43 guest_image_path: str,44 switch_name: str,45 cores: int = 2,46 memory: int = 2048,47 stop_existing_vm: bool = True,48 ) -> None:49 if stop_existing_vm:50 self.delete_vm(name)51 # create a VM in hyperv52 powershell = self.node.tools[PowerShell]53 powershell.run_cmdlet(54 f"New-VM -Name {name} -Generation 1 "55 f"-MemoryStartupBytes {memory}MB -BootDevice VHD "56 f"-VHDPath {guest_image_path} -SwitchName {switch_name}",57 force_run=True,58 )59 # set cores and memory type60 powershell.run_cmdlet(61 f"Set-VM -Name {name} -ProcessorCount {cores} -StaticMemory "62 "-CheckpointType Disabled",63 force_run=True,64 )65 # add disks66 disk_info = powershell.run_cmdlet(67 "(Get-Disk | Where-Object {$_.OperationalStatus -eq 'offline'}).Number",68 force_run=True,69 )70 matched = re.findall(r"\d+", disk_info)71 disk_numbers = [int(x) for x in matched]72 for disk_number in disk_numbers:73 powershell.run_cmdlet(74 f"Add-VMHardDiskDrive -VMName {name} -DiskNumber {disk_number} "75 "-ControllerType 'SCSI'",76 force_run=True,77 )78 # start vm79 powershell.run_cmdlet(80 f"Start-VM -Name {name}",81 force_run=True,82 )83 # wait for vm start84 timeout_start = time.time()85 is_ready = False86 self._log.debug(f"Waiting for VM {name} to start")87 while time.time() - timeout_start < 600:88 try:89 if self.get_ip_address(name):90 self._log.debug(f"VM {name} is ready")91 is_ready = True92 break93 except LisaException as e:94 self._log.debug(f"VM {name} not ready: {e}")95 time.sleep(10)96 if not is_ready:97 raise LisaException(f"VM {name} did not start")98 def exists_switch(self, name: str) -> bool:99 output = self.node.tools[PowerShell].run_cmdlet(100 f"Get-VMSwitch -Name {name}",101 fail_on_error=False,102 force_run=True,103 )104 return output.strip() != ""105 def delete_switch(self, name: str) -> None:106 if self.exists_switch(name):107 self.node.tools[PowerShell].run_cmdlet(108 f"Remove-VMSwitch -Name {name} -Force",109 force_run=True,110 )111 def create_switch(self, name: str) -> None:112 # remove switch if it exists113 self.delete_switch(name)114 # create a new switch115 self.node.tools[PowerShell].run_cmdlet(116 f"New-VMSwitch -Name {name} -SwitchType Internal",117 force_run=True,118 )119 def get_switch_interface_index(self, switch_name: str) -> int:120 output = self.node.tools[PowerShell].run_cmdlet(121 f"(Get-NetAdapter -Name '*{switch_name}*').ifindex",122 force_run=True,123 )124 return int(output.strip())125 def exists_nat(self, name: str) -> bool:126 output = self.node.tools[PowerShell].run_cmdlet(127 f"Get-NetNat -Name {name}",128 fail_on_error=False,129 force_run=True,130 )131 return output.strip() != ""132 def delete_nat(self, name: str) -> None:133 if self.exists_nat(name):134 self.node.tools[PowerShell].run_cmdlet(135 f"Remove-NetNat -Name {name} -Confirm:$false",136 force_run=True,137 )138 def create_nat(self, name: str, ip_range: str) -> None:139 # delete NAT if it exists140 self.delete_nat(name)141 # create a new NAT142 self.node.tools[PowerShell].run_cmdlet(143 f"New-NetNat -Name {name} -InternalIPInterfaceAddressPrefix '{ip_range}' ",144 force_run=True,145 )146 def delete_nat_networking(self, switch_name: str, nat_name: str) -> None:147 # Delete switch148 self.delete_switch(switch_name)149 # delete NAT150 self.delete_nat(nat_name)151 def setup_nat_networking(self, switch_name: str, nat_name: str) -> None:152 """153 Setup NAT networking154 Reference: https://docs.microsoft.com/en-us/virtualization/hyper-v-on-windows/user-guide/setup-nat-network # noqa155 """156 # create a new switch157 self.create_switch(switch_name)158 # find interface index of the switch159 interface_index = self.get_switch_interface_index(switch_name)160 # set switch interface as gateway for NAT161 self.node.tools[PowerShell].run_cmdlet(162 "New-NetIPAddress -IPAddress 192.168.5.1 "163 f"-InterfaceIndex {interface_index} -PrefixLength 24",164 force_run=True,165 )166 # create a new NAT167 self.create_nat(nat_name, "192.168.5.0/24")168 def get_ip_address(self, name: str) -> str:169 # verify vm is running170 assert_that(self.exists_vm(name)).is_true()171 # get vm ip address172 output = self.node.tools[PowerShell].run_cmdlet(173 f"Get-VM -Name {name} | Select -ExpandProperty networkadapters | select"174 " ipaddresses",175 force_run=True,176 )177 # regex match for ip address178 match = re.search(self.IP_REGEX, output)179 ip_address = match.group(0) if match else ""180 # raise exception if ip address is not found181 if not ip_address:182 raise LisaException(f"Could not find IP address for VM {name}")183 return ip_address184 def exist_port_forwarding(185 self,186 nat_name: str,187 ) -> bool:188 output = self.node.tools[PowerShell].run_cmdlet(189 f"Get-NetNatStaticMapping -NatName {nat_name}",190 fail_on_error=False,191 force_run=True,192 )193 return output.strip() != ""194 def delete_port_forwarding(self, nat_name: str) -> None:195 if self.exist_port_forwarding(nat_name):196 self.node.tools[PowerShell].run_cmdlet(197 f"Remove-NetNatStaticMapping -NatName {nat_name} -Confirm:$false",198 force_run=True,199 )200 def setup_port_forwarding(201 self,202 nat_name: str,203 host_port: int,204 guest_ip: str,205 host_ip: str = "0.0.0.0",206 guest_port: int = 22,207 ) -> None:208 # create new port forwarding209 self.node.tools[PowerShell].run_cmdlet(210 f"Add-NetNatStaticMapping -NatName {nat_name} "211 f"-ExternalIPAddress {host_ip} -ExternalPort {host_port} "212 f"-InternalIPAddress {guest_ip} -InternalPort {guest_port} -Protocol TCP",213 force_run=True,214 )215 def exists_virtual_disk(self, name: str) -> bool:216 output = self.node.tools[PowerShell].run_cmdlet(217 f"Get-VirtualDisk -FriendlyName {name}",218 fail_on_error=False,219 force_run=True,220 )221 return output.strip() != ""222 def delete_virtual_disk(self, name: str) -> None:223 if self.exists_virtual_disk(name):224 self.node.tools[PowerShell].run_cmdlet(225 f"Remove-VirtualDisk -FriendlyName {name} -confirm:$false",226 force_run=True,227 )228 def create_virtual_disk(self, name: str, pool_name: str, columns: int = 2) -> None:229 # remove existing virtual disk, if it exists230 self.delete_virtual_disk(name)231 # create a new virtual disk from `pool_name`232 self.node.tools[PowerShell].run_cmdlet(233 f"New-VirtualDisk -FriendlyName {name} "234 f"-StoragePoolFriendlyName {pool_name} -Interleave 65536 "235 f"-UseMaximumSize -NumberOfColumns {columns} "236 "-ResiliencySettingName Simple",237 force_run=True,238 )239 def _check_exists(self) -> bool:240 try:241 self.node.tools[PowerShell].run_cmdlet(242 "Get-VM",243 force_run=True,244 )245 self._log.debug("Hyper-V is installed")246 return True247 except LisaException as e:248 self._log.debug(f"Hyper-V not installed: {e}")249 return False250 def _install(self) -> bool:251 assert isinstance(self.node.os, Windows)252 # enable hyper-v253 self.node.tools[PowerShell].run_cmdlet(254 "Install-WindowsFeature -Name Hyper-V -IncludeManagementTools",255 force_run=True,256 )257 # reboot node258 self.node.reboot()...

Full Screen

Full Screen

run-cmdlet.py

Source:run-cmdlet.py Github

copy

Full Screen

...16# Python 3.5+17# Powershell 5.0+18import subprocess19# Reusable code block for running a powershell cmdlet from a python script20def run_cmdlet():21 subprocess.run(["C:/Windows/system32/WindowsPowerShell/v1.0/powershell.exe", "Get-Command", "-CommandType", "Cmdlet"], shell=False)22run_cmdlet()23 24# NOTES, TROUBLESHOOTING, AND OTHER INFO25# 26# Be sure the path in the first argument of subprocess.run points to your27# Powershell executable.28#29# Be sure to add each argument or string as a separate python string in quotes.30# This is necessary since we are running all scripts with shell=False for31# security reasons. To learn more about this, see the Python docs here:...

Full Screen

Full Screen

powershell2python.py

Source:powershell2python.py Github

copy

Full Screen

...6args = ["powershell.exe", "-Command", r"-"]7cmdlet = "Get-ADUser -Filter{displayName -like 'Artem Ageev'} \r\n"89def main():10 print(run_cmdlet(cmdlet))1112def run_cmdlet(cmdlet):13 process = subprocess.Popen(args, stdin = subprocess.PIPE, stdout = subprocess.PIPE) 14 process.stdin.write(str.encode(cmdlet))15 result = process.communicate()[0].decode("utf-8").replace("\r\n", "\n")16 return result1718if __name__ == '__main__': ...

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run lisa automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful