def guest_add(self, guest_name, image_path): """ Create a new virtual machine. :param guest_name: the name for the new virtual machine :param image_path: the path for the guest image which from the remote web :return: guest already existed, return None, create successfully, return True, else, return False """ if self.guest_exist(guest_name): logger.warning(f'Guest {guest_name} has already existed') return self.guest_image(guest_name, image_path) switch_name = self.virtual_switch() if '8.' in guest_name: options = f'-MemoryStartupBytes 2GB -SwitchName {switch_name} -Generation 2' else: options = f'-MemoryStartupBytes 1GB -SwitchName {switch_name} -Generation 1' cmd = f"PowerShell New-VM -Name {guest_name} -VHDPath \"C:\hyperv_img\{guest_name}.vhdx\" {options}" ret, _ = self.ssh.runcmd(cmd) if not ret and self.guest_exist(guest_name): logger.info("Succeeded to add hyperv guest") if '8.' in guest_name: cmd = f"PowerShell Set-VMFirmware -VMName {guest_name} -EnableSecureBoot off" self.ssh.runcmd(cmd) else: raise FailException("Failed to add hyperv guest")
def put_dir(self, local_dir, remote_dir): """ Upload all files from directory to a remote directory :param local_dir: all files from local path to be uploaded. :param remote_dir: a remote path where the uploaded files will be placed. """ sftp, conn = self._transfer() for root,dirs,files in os.walk(local_dir): for filespath in files: local_file = os.path.join(root,filespath) a = local_file.replace(local_dir,'') remote_file = os.path.join(remote_dir,a) try: sftp.put(local_file,remote_file) except Exception as e: sftp.mkdir(os.path.split(remote_file)[0]) sftp.put(local_file,remote_file) for name in dirs: local_path = os.path.join(root,name) a = local_path.replace(local_dir,'') remote_path = os.path.join(remote_dir,a) try: sftp.mkdir(remote_path) except Exception as e: logger.info(e) conn.close()
def info(self): """ Get the VMhost info :return: the VMHosts info """ cmd = f'{self.cert} ConvertTo-Json @(Get-VMHost | Select * -ExcludeProperty ExtensionData)' ret, output = self.ssh.runcmd(cmd) output = self._format(ret, output) for host in output: logger.info(f"Get ESXi Host: {host['Name']}") return output
def info(self): """ Get the VMhost info :return: the VMHosts info """ cmd = 'PowerShell ConvertTo-Json @(Get-VMHost)' ret, output = self.ssh.runcmd(cmd) output = self._format(ret, output) for host in output: logger.info(f"Get Hyperv master: {host['Name']}") return output
def guest_resume(self, guest_name): """ Resume virtual machines :param guest_name: the virtual machines you want to resume. :return: resume successfully, return True, else, return False. """ cmd = f'PowerShell Resume-VM -Name {guest_name}' ret, _ = self.ssh.runcmd(cmd) if not ret and self.guest_search(guest_name)['guest_state'] is 2: logger.info("Succeeded to resume hyperv guest") else: raise FailException("Failed to resume hyperv guest")
def guest_suspend(self, guest_name): """ Suspend virtual machines. :param guest_name: the virtual machines you want to suspend. :return: suspend successfully, return True, else, return False. """ cmd = f'PowerShell Suspend-VM -Name {guest_name}' ret, _ = self.ssh.runcmd(cmd) if not ret and self.guest_search(guest_name)['guest_state'] is 9: logger.info("Succeeded to suspend hyperv guest") else: raise FailException("Failed to suspend hyperv guest")
def guest_start(self, guest_name): """ Power on virtual machines. :param guest_name: the virtual machines you want to power on. :return: power on successfully, return True, else, return False. """ cmd = f'PowerShell Start-VM -Name {guest_name}' ret, _ = self.ssh.runcmd(cmd) if not ret and self.guest_search(guest_name)['guest_state'] is 2: logger.info("Succeeded to start hyperv guest") else: raise FailException("Failed to start vcenter guest")
def guest_suspend(self, guest_name): """ Suspend virtual machines. :param guest_name: the virtual machines you want to suspend. :return: suspend successfully, return True, else, return False. """ cmd = f'{self.cert} Suspend-VM -VM {guest_name} -Confirm:$false' ret, _ = self.ssh.runcmd(cmd) if not ret and self.guest_search(guest_name)['guest_state'] is 2: logger.info("Succeeded to suspend vcenter guest") return True else: logger.info("Failed to suspend vcenter guest") return False
def guest_stop(self, guest_name): """ Power off virtual machines. :param guest_name: the virtual machines you want to power off. :return: stop successfully, return True, else, return False. """ cmd = f'{self.cert} Stop-VM -VM {guest_name} -Kill -Confirm:$false' ret, _ = self.ssh.runcmd(cmd) if not ret and self.guest_search(guest_name)['guest_state'] is 0: logger.info("Succeeded to stop vcenter guest") return True else: logger.info("Failed to stop vcenter guest") return False
def guest_resume(self, guest_name): """ Resume virtual machines :param guest_name: the virtual machines you want to resume. :return: resume successfully, return True, else, return False. """ cmd = f'{self.cert} Start-VM -VM {guest_name} -Confirm:$false' ret, _ = self.ssh.runcmd(cmd) if not ret and self.guest_search(guest_name)['guest_state'] is 1: logger.info("Succeeded to resume vcenter guest") return True else: logger.info("Failed to resume vcenter guest") return False
def guest_del(self, guest_name): """ Remove the specified virtual machines from the hyperv Server system. :param guest_name: the virtual machines you want to remove. :return: remove successfully, return True, else, return False. """ if self.guest_search(guest_name)['guest_state'] is not 3: self.guest_stop(guest_name) cmd = f'PowerShell Remove-VM {guest_name} -force' ret, _ = self.ssh.runcmd(cmd) if not ret and not self.guest_exist(guest_name): logger.info("Succeeded to delete hyperv guest") else: raise FailException("Failed to delete hyperv guest")
def guest_exist(self, guest_name): """ Check if the hyperv guest exists :param guest_name: the name for the guest :return: guest exists, return True, else, return False. """ cmd = "PowerShell Get-VM" ret, output = self.ssh.runcmd(cmd) if not ret and guest_name in output: logger.info(f'Succeed to find guest {guest_name }') return True else: logger.info(f'Failed to find guest {guest_name}') return False
def guest_del(self, guest_name): """ Remove the specified virtual machines from the vCenter Server system. :param guest_name: the virtual machines you want to remove. :return: remove successfully, return True, else, return False. """ if self.guest_search(guest_name)['guest_state'] is not 1: self.guest_stop(guest_name) cmd = f'{self.cert} Remove-VM -VM {guest_name} -DeletePermanently -Confirm:$false' ret, _ = self.ssh.runcmd(cmd) if not ret and not self.guest_exist(guest_name): logger.info("Succeeded to delete vcenter guest") return True else: logger.error("Succeeded to delete vcenter guest") return False
def guest_image(self, guest_name, image_path): """ Prepare the guest image for hyperv hypervisor :param guest_name: the name for the new virtual machine :param image_path: the path for the guest image :return: """ cmd = 'PowerShell New-Item -path C:\ -Name hyperv_img -Type Directory' self.ssh.runcmd(cmd) cmd = 'PowerShell Get-ChildItem C:\hyperv_img' ret, output = self.ssh.runcmd(cmd) if not ret and guest_name in output: logger.info("hyperv image is exist") else: cmd = f"PowerShell (New-Object System.Net.WebClient).DownloadFile(" \ f"'{image_path}', 'C:\hyperv_img\{guest_name}.vhdx')" ret, output = self.ssh.runcmd(cmd) if not ret: logger.info("succeeded to download hyperv image") else: raise FailException("Failed to download hyperv image")
def guest_add(self, host, host_ssh_user, host_ssh_pwd, guest_name, image_path): """ Create a new virtual machine. :param host: the host on which you want to create the new virtual machine. :param host_ssh_user: the ssh username for the host :param host_ssh_pwd: the ssh password for the host :param guest_name: the name for the new virtual machine :param image_path: the path for the guest image which from the remote web :return: create successfully, return True, else, return False """ self.guest_images(host, host_ssh_user, host_ssh_pwd, guest_name, image_path) data_store = self.host_search(host)["host_data_store"] vmxFile = f"'[{data_store}] {guest_name}/{guest_name}.vmx'" cmd = f'{self.cert} New-VM -VMFilePath {vmxFile} -VMHost {host}' ret, _ = self.ssh.runcmd(cmd) if not ret and self.guest_exist(guest_name): logger.info("Succeeded to add vcenter guest") self.guest_start(guest_name) return True else: logger.error("Failed to add vcenter guest") return False
def runcmd(self, cmd): """Executes SSH command on remote hostname. :param str cmd: The command to run """ ssh = self._connect() logger.info(">>> {}".format(cmd)) stdin, stdout, stderr = ssh.exec_command(cmd) code = stdout.channel.recv_exit_status() stdout, stderr = stdout.read(), stderr.read() ssh.close() if not stderr: logger.info("<<< stdout\n{}".format(stdout.decode())) return code, stdout.decode() else: logger.info("<<< stderr\n{}".format(stderr.decode())) return code, stderr.decode()