python 自動建立Hype-V虛擬機器指令碼
阿新 • • 發佈:2021-09-28
安裝模組
pip install pywinrm
指令碼如下
#!/usr/bin/env python3 # coding=utf-8 # author:LJX # describe:一鍵建立hype-v虛擬機器 # createdate:2021.5.26 import winrm class VM(object): ''' # 1、檢視winrm服務狀態。預設沒有啟動 winrm enumerate winrm/config/listener # 2、啟動伺服器(網路型別改為專有網路) winrm quickconfig # 3、開啟防火牆 netsh advfirewall firewall set rule group="Windows 遠端管理" new enable=yes # 4、啟動 winrm quickconfig # 5、檢視 winrm enumerate winrm/config/listener # 5、為winrm service 配置auth winrm set winrm/config/service/auth @{Basic="true"} # 7、為winrm service 配置加密方式為允許非加密 winrm set winrm/config/service @{AllowUnencrypted="true"} ''' def __init__(self): self.host = "xxxx" self.port = "xxxx" self.user = "xxxxx" self.passwd = 'xxxx' self.linuxfile = r"xxxxxxx" self.winfile = r"xxxxxx" self.linuxPath = '''D:\{0}'''.format(self.linuxfile) self.winPath = '''D:\{0}'''.format(self.winfile) self.network = "wan" self.wintest = winrm.Session('http://{0}:{1}/wsman'.format(self.host, self.port), auth=(self.user, self.passwd)) def exec_ps(self, commond,msg): ret = self.wintest.run_ps(commond) if ret.status_code == 0: print(msg + "成功") elif ret.status_code == 1: print(msg + "失敗") print(str(ret.std_out, "utf-8")) def add_vm(self, params): hostname = params["ip"] +"-"+ params["projectName"] path = "{0}:\{1}".format(params["diskPath"], hostname) self.exec_ps(r"new-item -path {0} -type directory".format(path),"建立虛擬機器目錄") # 2、 if params["sysType"] == "linux": self.exec_ps(r'''copy-item {0} {1}'''.format(self.linuxPath, path),"複製系統") self.exec_ps( r"New-VM -VHDPath {0}\{1} -MemoryStartupBytes {2}GB -Name {3} -SwitchName {4}".format(path, self.linuxfile, params["mem"], hostname, self.network), "建立虛擬機器" ) elif params["sysType"] == "windows": self.exec_ps(r'''copy-item {0} {1}'''.format(self.winPath, path),"複製系統") self.exec_ps( r"New-VM -VHDPath {0}\{1} -MemoryStartupBytes {2}GB -Name {3} -SwitchName {4}".format(path, self.winfile, params["mem"], hostname, self.network), "建立虛擬機器" ) self.exec_ps("Set-VMProcessor -VMName {0} -Count {1}".format(hostname, params["core"]),"設定核心數") if params["otherDisk"]["enable"]: otherDiskPath = "{0}\{1}".format(path,params["otherDisk"]["name"]) self.exec_ps("New-VHD -Path {0} -SizeBytes {1}GB".format(otherDiskPath,params["otherDisk"]["size"]),"建立磁碟") self.exec_ps("Add-VMHardDiskDrive -VMName {0} -Path {1}".format(hostname,otherDiskPath),"虛擬機器掛載磁碟") if __name__ == "__main__": vm_params = { "projectName": "vmtest", "ip": "xxxxxx", "mem": 4, "core": 4, "disk": 100, "diskPath": "F", "sysType": "linux", "otherDisk":{ "name": "disk1.vhdx", "enable": True, "size": 10, } } vm = VM() vm.add_vm(vm_params)