def enableps(machinename, username, password): result = None conn = None pythoncom.CoInitialize() try: LogHelper.append("try to enable ps on {0} with {1}:{2}".format( machinename, username, password)) conn = wmi.WMI(computer=machinename, user=username, password=password, namespace=r'root\cimv2') except Exception as e: print(str(e)) LogHelper.append(str(conn)) LogHelper.append("connect wmi failed on {0} with {1}:{2}".format( machinename, username, password)) conn == None result == False if conn != None: """ try: ## this need to be change, a service running can't be regarded as PS enabled svcs = conn.Win32_Service() for svc in svcs: if svc.Name == 'WinRM' and svc.State == 'Running': result = True LogHelper.append("winrm service is running on {0} with {1}:{2}".format(machinename, username, password)) break except Exception as e: print(str(e)) LogHelper.append("check winrm service failed on {0} with {1}:{2}".format(machinename, username, password)) if result != True: """ """ try: cmd_call = "cmd /c PowerShell -Command \"Set-WSManQuickConfig -Force\"" print(cmd_call) id, value = conn.Win32_Process.Create(CommandLine=cmd_call) print(id,value) watcher = conn.watch_for(notification_type="Deletion", wmi_class="Win32_Process", delay_secs=1, ProcessId=id) LogHelper.append("waiting Set-WSManQuickConfig process {0} complete on {1}".format(id, machinename)) try: LogHelper.append("waiting 300 seconds Set-WSManQuickConfig process {0} complete on {1}".format(id, machinename)) error_log = watcher(timeout_ms=300000) LogHelper.append(error_log) except wmi.x_wmi_timed_out: pythoncom.PumpWaitingMessages() LogHelper.append("timout out Set-WSManQuickConfig process {0} complete on {1} {2}".format(id, machinename, error_log)) time.sleep(10) except Exception as e: print(str(e)) LogHelper.append("Set-WSManQuickConfig failed on {0} with {1}:{2}".format(machinename, username, password)) """ try: cmd_call = "cmd /c PowerShell -Command \"Enable-PSRemoting -Force\"" print(cmd_call) id, value = conn.Win32_Process.Create(CommandLine=cmd_call) print(id, value) watcher = conn.watch_for(notification_type="Deletion", wmi_class="Win32_Process", delay_secs=1, ProcessId=id) LogHelper.append( "waiting EnablePS process {0} complete on {1}".format( id, machinename)) try: LogHelper.append( "waiting 300 seconds EnablePS process {0} complete on {1}" .format(id, machinename)) error_log = watcher(timeout_ms=300000) LogHelper.append(error_log) except wmi.x_wmi_timed_out: pythoncom.PumpWaitingMessages() LogHelper.append( "timout out EnablePS process {0} complete on {1} {2}". format(id, machinename, error_log)) time.sleep(30) LogHelper.append( "enable ps succeed on {0} with {1}:{2}".format( machinename, username, password)) result = True except Exception as e: print(str(e)) LogHelper.append( "enable PSRemoting failed on {0} with {1}:{2}".format( machinename, username, password)) result = False pythoncom.CoUninitialize() return result
def getVMPropertyValue(hostname, username, password, vmname, vmid, property): try: print('getvmproperty') osname = WMIHelper.getMachineProperty(hostname, username, password, 'OSName') print(osname) virtualnamespace = WMIHelper.getVirtualizationNamespace(osname) print(virtualnamespace) wql = "SELECT GuestIntrinsicExchangeItems FROM Msvm_KvpExchangeComponent where SystemName='%s'" % vmid dt = WMIHelper.executeWMIQuery(hostname, username, password, virtualnamespace, wql) property_dict = {} for idt in dt: #print(idt) propertyxml = idt.GuestIntrinsicExchangeItems #print(propertyxml) for eachpro in propertyxml: #print(eachpro) eachprodict = XMLHelper.parsexmltodict(eachpro) property_dict.update(eachprodict) print(property_dict) except Exception as e: LogHelper.append(' '.join([r'getVMPropertyValue error:', str(e)])) #print(property) #print(property_dict.get(property)) return property_dict.get(property)
def parsexmltodict(xmldt): dom = minidom.parseString(xmldt) eroot = dom.documentElement itemlist = eroot.getElementsByTagName('PROPERTY') for item in itemlist: # print(item) if item.getAttribute('NAME') == 'Data': elements = item.getElementsByTagName('VALUE') try: value = elements[0].firstChild.nodeValue except Exception as e: value = None LogHelper.append(' '.join( [r'parsexmltodict:find Data Value error:', str(e)])) continue if item.getAttribute('NAME') == 'Name': elements = item.getElementsByTagName('VALUE') try: key = elements[0].firstChild.nodeValue # print(key) except Exception as e: key = None LogHelper.append(' '.join( [r'parsexmltodict:find Name Value error:', str(e)])) continue dtdict = {key: value} return dtdict
def getMachineProperty(machinename, username, password, property): result = None try: namespace = r"root\cimv2" if property == 'OSName': wql = "select Caption from Win32_OperatingSystem" print(wql) print(machinename) print(username) print(password) dt = WMIHelper.executeWMIQuery(machinename, username, password, namespace, wql) for wmiobj in dt: result = wmiobj.Caption elif property == 'Version': wql = "select Version from Win32_OperatingSystem" dt = WMIHelper.executeWMIQuery(machinename, username, password, namespace, wql) for wmiobj in dt: result = wmiobj.Version elif property == 'OSLanguage': wql = "select OSLanguage from Win32_OperatingSystem" dt = WMIHelper.executeWMIQuery(machinename, username, password, namespace, wql) for wmiobj in dt: result = wmiobj.OSLanguage except Exception as e: LogHelper.append(' '.join([r'getMachineOSName error:', str(e)])) return result
def updateProperty(DB, machine, type, location, property): if type == 'hm': if location == 'sh': hmobj = SHHost elif location == 'red': hmobj = REDHost try: hm = hmobj.objects.get(machine_name=machine.machineName) if property == 'compliant': hm.compliant = machine.compliant if property == 'lastcu': hm.lastcu = machine.lastCU hm.save() except hmobj.DoesNotExist: print('DB.updateproperty error: host not found or save failed') LogHelper.append( 'DB.updateproperty error: host not found or save failed') elif type == 'vm': if location == 'sh': vmobj = SHVirtualMachine elif location == 'red': vmobj = REDVirtualMachine try: vm = vmobj.objects.get(vmid=machine.vmid) if property == 'compliant': vm.compliant = machine.compliant if property == 'lastcu': vm.lastcu = machine.lastCU vm.save() except Exception as e: print(str(e)) LogHelper.append( 'update property error: update or create vm object failed')
def enumRegValue(machinename, username, password, regkey): regkeyvalue = {} print(regkey) pythoncom.CoInitialize() try: r = wmi.WMI(computer=machinename, user=username, password=password, namespace=r"root\cimv2").StdRegProv print(regkey) pprint(r.__dict__) HKLM = 0x80000002 result, valuenames, types = r.EnumValues(hDefKey=HKLM, sSubKeyName=regkey) print(valuenames) for valuename in valuenames: LogHelper.append("Registry value found {0}".format(valuename)) result, value = r.GetStringValue(hDefKey=HKLM, sSubKeyName=regkey, sValueName=valuename) regkeyvalue[valuename] = value print(regkeyvalue) return regkeyvalue except Exception as e: traceback.print_exc() print("check registry failed") LogHelper.append("Get registry failed {0} with {1}:{2}".format( machinename, username, password)) finally: #pythoncom.CoUninitialize() pass
def getOSLang(self, machinename, username, password): langID = WMIHelper.getMachineProperty(self.machineName, self.userName, self.password, 'OSLanguage') LogHelper.append(" {0} Local:{1}".format(machinename, langID)) if langID == 1033: self.osLang = 'enu' elif langID == 2052: self.osLang = 'chs' elif langID == 1031: self.osLang = 'deu' return self.osLang
def getRegValue(machinename, username, password, regkey, regvalue): pythoncom.CoInitialize() try: r = wmi.WMI(computer=machinename, user=username, password=password, namespace=r"root\cimv2").StdRegProv HKLM = 0x80000002 result, valuenames, types = r.EnumValues(hDefKey=HKLM, sSubKeyName=regkey) for valuename in valuenames: if valuename == regvalue: LogHelper.append( "Registry value found {0}".format(valuename)) result, value = r.GetStringValue(hDefKey=HKLM, sSubKeyName=regkey, sValueName=regvalue) return value LogHelper.append("No registry value found {0}".format(names)) LogHelper.append("No registry value found {0} with {1}:{2}".format( machinename, username, password)) except Exception as e: print("check registry failed") LogHelper.append("Get registry failed {0} with {1}:{2}".format( machinename, username, password)) finally: #pythoncom.CoUninitialize() pass
def getRebootReg(machinename, username, password): pythoncom.CoInitialize() try: r = wmi.WMI(computer=machinename, user=username, password=password, namespace=r"root\cimv2").StdRegProv HKLM = 0x80000002 result, names = r.EnumKey( hDefKey=HKLM, sSubKeyName= r"SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update" ) for key in names: print(key) if key == 'RebootRequired': LogHelper.append("Reboot registry found {0}".format(key)) return True LogHelper.append("No registry found {0}".format(names)) LogHelper.append("No registry found {0} with {1}:{2}".format( machinename, username, password)) return False except Exception as e: print("check registry failed") LogHelper.append("Get registry failed {0} with {1}:{2}".format( machinename, username, password)) finally: pythoncom.CoUninitialize()
def get_ip(self): if self.ip == None or CMDHelper.testconnection(self.ip) == False: print('try to get ip by powershell...') LogHelper.append("get {0} ip by powershell".format( self.machineName)) self.ip = PowerShellHelper.getvmip(self.hostName, r'.\administrator', r'User@123', self.machineName) LogHelper.append("get {0} ip {1} by powershell".format( self.machineName, self.ip)) if self.ip == None: return None return self.ip
def getvmid(hostname, username, password, vmname): osname = WMIHelper.getMachineProperty(hostname, username, password, 'OSName') virtualnamespace = WMIHelper.getVirtualizationNamespace(osname) wql = "SELECT Name FROM Msvm_ComputerSystem where EnabledState=2 and Caption='Virtual Machine' and Elementname ='%s'" % vmname print(wql) try: dt = WMIHelper.executeWMIQuery(hostname, username, password, virtualnamespace, wql) for idt in dt: vmid = idt.Name return vmid except Exception as e: LogHelper.append(' '.join([r'getvmid error:', str(e)]))
def getvmip(hostname, username, password, vmname): try: vmid = WMIHelper.getvmid(hostname, username, password, vmname) print(vmid) ips = WMIHelper.getVMPropertyValue(hostname, username, password, vmname, vmid, 'RDPAddressIPv4') print(ips) iparray = ips.split(';') for ip in iparray: if CMDHelper.testconnection(ip): print(ip) return ip except Exception as e: LogHelper.append(' '.join([r'getvmip error:', str(e)])) return None
def rebootMachine(machinename, username, password): pythoncom.CoInitialize() try: conn = wmi.WMI(computer=machinename, user=username, password=password, namespace=r"root\cimv2") conn = wmi.WMI(computer=machinename, privileges=["RemoteShutdown"]) os = conn.Win32_OperatingSystem(Primary=1)[0] os.Reboot() except Exception as e: print("Reboot failed") LogHelper.append("reboot failed {0} with {1}:{2}".format( machinename, username, password)) finally: pythoncom.CoUninitialize()
def disableps(machinename, username, password): #pythoncom.CoInitialize() try: conn = wmi.WMI(computer=machinename, user=username, password=password, namespace=r"root\cimv2") cmd_call = r"cmd /c Powershell -Command \"Disable-PSRemoting\"" id, value = conn.Win32_Process.Create(CommandLine=cmd_call) print(id, value) except Exception as e: print("disalbe WinRm failed") LogHelper.append("Disable Winrm failed {0} with {1}:{2}".format( machinename, username, password)) finally: pass
def invoke_wuinstall(machinename, username, password): args = [ r'Powershell', r'.\\PowerShellScripts\\ScheduleWUJob.ps1', r'-MachineName', machinename, r'-Username', username, r'-Password', password ] print(args) try: p = subprocess.Popen(args, stdout=subprocess.PIPE) dt = p.stdout.read() LogHelper.append(dt) except Exception as e: traceback.print_exc() LogHelper.append( "Powershell: Shedule WUJob failed for{0} with {1}:{2}".format( machinename, username, password)) return dt
def executeWMIQuery(machinename, username, password, namespace, wql): result = None try: print(machinename) print(namespace) print(wql) pythoncom.CoInitialize() remotewmi = wmi.WMI(computer=machinename, user=username, password=password, namespace=namespace) result = remotewmi.query(wql) except Exception as e: print(str(e)) LogHelper.append(' '.join([r'executeWMIQuery error:', str(e)])) finally: #pythoncom.CoUninitialize() return result
def accountverify(machinename, username, password): pythoncom.CoInitialize() try: conn = wmi.WMI(computer=machinename, user=username, password=password, namespace=r'root\cimv2') LogHelper.append("accountverify succeed {0} with {1}:{2}".format( machinename, username, password)) result = True except Exception as e: LogHelper.append( "accountverify failed {0} with {1}:{2} {3}".format( machinename, username, password, str(e))) result = False finally: pythoncom.CoUninitialize() return result
def getInstalledUpdate(self): if self.get_ip() == None: LogHelper.append( "get update error ip/username/password not right {0}:{1} using {2}:{3} " .format(self.machineName, self.ip, self.userName, self.password)) return None """ if self.set_credential() == False: LogHelper.append("get update error ip/username/password not right {0}:{1} using {2}:{3} ".format(self.machineName, self.ip, self.userName, self.password)) return None """ cre = self.set_credential() self.getOSLang() LogHelper.append("try to get {0}:{1} update using {2}:{3}".format( self.machineName, self.ip, self.userName, self.password)) return super(VirtualMachine, self).getInstalledUpdate(self.ip, self.userName, self.password, self.osLang)
def testpsremoting(machinename, username, password): args = [ r"PowerShell", r".\\PowerShellScripts\\TestPSRemoting.ps1", r"-MachineName", machinename, r"-Username", username, r"-Password", password ] print(args) print('Powershell TestPSRemoting for {0}'.format(machinename)) try: p = subprocess.Popen(args, stdout=subprocess.PIPE) dt = p.stdout.read() dt = dt.decode(encoding='utf-8') dt = int(dt) if (dt == 1): return True except Exception as e: print("Powershell TestPSRemoting Exception " + str(e)) LogHelper.append( "Powershell TestPSRemoting exception for {0}".format( machinename)) return False
def hypervexists(machinename, username, password): osname = WMIHelper.getMachineProperty(machinename, username, password, 'OSName') print(osname) namespace = WMIHelper.getVirtualizationNamespace(osname) result = None pythoncom.CoInitialize() try: remotewmi = wmi.WMI(computer=machinename, user=username, password=password, namespace=namespace) result = True except Exception as e: LogHelper.append(' '.join( [r'hyperv namespace test error:', str(e)])) result = False finally: pythoncom.CoUninitialize() return result
def enum_namespace(machinename, username, password, namespace): pythoncom.CoInitialize() namespaces = None print(namespace) try: r = wmi.WMI(computer=machinename, user=username, password=password, namespace=namespace) wql = "SELECT * FROM __NAMESPACE" namespaces = r.query(wql) print(namespaces) except Exception as e: print("get namespace failed") LogHelper.append( "Get wmi namespaces failed {0} with {1}:{2}".format( machinename, username, password)) finally: #pythoncom.CoUninitialize() pass print(namespaces) return namespaces
def getupdate(machinename, username, password, lang='enu'): print("scan %s started..." % machinename) #LogHelper.append("Powershell:try to scan {0} with account {1}:{2}".format(machinename, username, password)) args = [ r"PowerShell", r".\\PowerShellScripts\\ScanAllInstalledHotfixes.ps1", r"-MachineName", machinename, r"-Username", username, r"-Password", password ] print(args) updateinfo = [] try: p = subprocess.Popen(args, stdout=subprocess.PIPE) dt = p.stdout.read() #print(dt) # this is a byte string start with b', contains data with different encoding like gbk # windows-1250, will be handled in OutputHelper if lang == 'enu': dt = dt.decode('utf-8', errors='ignore') elif lang == 'chs': dt = dt.decode('gbk', errors='ignore') elif lang == 'deu': dt = dt.decode('windows-1250', errors='ignore') #print(dt) if dt != None: updatelist = OutputHelper.parseJson(dt) else: updatelist = None print('%s updates' % machinename) for update in updatelist: updateinfo.append(update.todict()) #print(update.updateTitle) except Exception as e: print(traceback.print_exc()) LogHelper.append( "Powershell: getUpdate failed for{0} with {1}:{2}".format( machinename, username, password)) return json.dumps(updateinfo)
def getvmip(hostname, username, password, vmname): vmname = '\'' + vmname + '\'' args = [ r"PowerShell", r".\\PowerShellScripts\\GetVMIP.ps1", r"-MachineName", hostname, r"-Username", username, r"-Password", password, r'-VMName', vmname ] print(args) print('Powershell getvmip for {0} on {1}'.format(vmname, hostname)) try: p = subprocess.Popen(args, stdout=subprocess.PIPE) dt = p.stdout.read() LogHelper.append(dt) dt = dt.decode(encoding='utf-8') ip = dt.strip() if ip == '': print('ip not found') return None else: return ip except Exception as e: print("powershell getvmip exception " + str(e)) LogHelper.append("getvmip failed for {0}".format(vmname)) return None
def invokeWUInstall(self, machinename, username, password): print("check PS Remoting on %s..." % machinename) if PowerShellHelper.testpsremoting(machinename, username, password) == True: pass else: if WMIHelper.enableps(machinename, username, password) == False: LogHelper.append( "EnablePSRemoting failed {0}".format(machinename)) print("invokeWUInstall on %s..." % machinename) ret = '' try: ret = PowerShellHelper.invoke_wuinstall(machinename, username, password) except Exception as e: LogHelper.append(str(e)) LogHelper.append( "Powershell: invoke wuinstall failed for {0} {1} with {2}:{3}". format(self.machineName, machinename, username, password)) return ret
def check_VS(machinename, username, password): #pythoncom.CoInitialize() try: r = wmi.WMI(computer=machinename, user=username, password=password, namespace=r"root\cimv2").StdRegProv HKLM = 0x80000002 HKCR = 0X80000000 result, names = r.EnumKey(hDefKey=HKCR, sSubKeyName=r'') for key in names: key_check = re.match(r'VisualStudio.DTE.(\d|\d\d).(\d|\d\d)', key) if key_check is not None: version = key_check.group()[17:] print(version) vsdevreg = r'SOFTWARE\Wow6432Node\Microsoft\DevDiv\vs\Servicing' + '\\' + version + '\\' + 'devenv' try: result, names = r.EnumKey(hDefKey=HKLM, sSubKeyName=vsdevreg) for key in names: return version except Exception as e: print("check vsdevreg registry failed") LogHelper.append( "Get vsdevreg registry failed {0} with {1}:{2}". format(machinename, username, password)) #LogHelper.append("No registry found {0}".format(names)) LogHelper.append( "No VisualStudio.DTE registry found {0} with {1}:{2}".format( machinename, username, password)) return False except Exception as e: print("check registry failed") LogHelper.append("Get registry failed {0} with {1}:{2}".format( machinename, username, password)) return False finally: #pythoncom.CoUninitialize() pass
def getInstalledUpdate(self, machinename, username, password, lang='enu'): print("check PS Remoting on %s..." % machinename) if PowerShellHelper.testpsremoting(machinename, username, password) == True: pass else: if WMIHelper.enableps(machinename, username, password) == False: LogHelper.append( "EnablePSRemoting failed {0}".format(machinename)) print("get update on %s..." % machinename) updatelist = [] try: LogHelper.append( "Powershell: getUpdate for{0} {1} with {2}:{3}".format( self.machineName, machinename, username, password)) updatelist = PowerShellHelper.getupdate(machinename, username, password, lang) except Exception as e: print(str(e)) LogHelper.append( "Powershell: getUpdate failed for{0} {1} with {2}:{3}".format( self.machineName, machinename, username, password)) return updatelist
def getAllVMsOnHost(hostname, username, password): osname = WMIHelper.getMachineProperty(hostname, username, password, 'OSName') virtualnamespace = WMIHelper.getVirtualizationNamespace(osname) # this query only return VMs in running # wql = "SELECT Name, Elementname FROM Msvm_ComputerSystem where EnabledState=2 and Caption='Virtual Machine'" # this query return all VMs including turned off VMs wql = "SELECT Name, Elementname FROM Msvm_ComputerSystem where Caption='Virtual Machine'" vms = [] try: from VirtualMachine import VirtualMachine dt = WMIHelper.executeWMIQuery(hostname, username, password, virtualnamespace, wql) for idt in dt: vm = VirtualMachine() vm.vmid = idt.Name print(vm.vmid) vm.machineName = idt.ElementName print(vm.machineName) vm.hostName = hostname print(vm.hostName) vms.append(vm) except Exception as e: LogHelper.append(' '.join(['getAllVMsOnHost error:', str(e)])) print(len(vms)) # initialize VM properties try: wql = "SELECT SystemName, GuestIntrinsicExchangeItems FROM Msvm_KvpExchangeComponent" dt = WMIHelper.executeWMIQuery(hostname, username, password, virtualnamespace, wql) for idt in dt: for index, vm in enumerate(vms): if vm.vmid != idt.SystemName: continue # print(vm.vmid) # print(idt.SystemName) property_dict = {} propertyxml = idt.GuestIntrinsicExchangeItems #print(idt) for eachpro in propertyxml: eachprodict = XMLHelper.parsexmltodict(eachpro) property_dict.update(eachprodict) try: print("trying get IP address...") ips = property_dict.get('RDPAddressIPv4') iparray = ips.split(';') for ip in iparray: if IPHelper.available(ip): vms[index].ip = ip break except Exception as e: LogHelper.append(' '.join( [r'getAllVMsOnHost get ip error:', str(e)])) print(str(e)) try: print("trying get OS Name...") vms[index].osName = property_dict.get('OSName') vms[index].osVersion = property_dict.get('OSVersion') except Exception as e: print("get os name error") LogHelper.append(' '.join( [r'getAllVMsOnHost get OS Name error:', str(e)])) try: print("trying get domain name...") vms[index].fullyQualifiedDomainName = property_dict.get( 'FullyQualifiedDomainName') vms[index].domainName = vms[ index].fullyQualifiedDomainName.split('.')[1] except Exception as e: print("get OS domain name error") LogHelper.append(' '.join([ r'getAllVMsOnHost get domain name error:', str(e) ])) try: print("trying get OSVersion...") vms[index].osVersion = property_dict.get('OSVersion') except Exception as e: print("get os Version error") LogHelper.append(' '.join( [r'getAllVMsOnHost get osversion error:', str(e)])) except Exception as e: LogHelper.append(' '.join( [r'getAllVMsOnHost Initialize VM property error:', str(e)])) for vm in vms: print(vm.machineName) print(vm.vmid) print(vm.ip) print(vm.osName) print(vm.osVersion) print(vm.domainName) return vms
def save(DB, machine, type, location): if type == 'hm': if location == 'sh': hmobj = SHHost elif location == 'red': hmobj = REDHost try: hm = hmobj.objects.get(machine_name=machine.machineName) hm.ip = machine.ip hm.installedupdate = machine.installedUpdate hm.os = machine.osName hm.osversion = machine.osVersion hm.oslang = machine.osLang hm.rebootrequired = machine.rebootRequired hm.lastscantime = machine.scancompletetime hm.compliant = machine.compliant hm.vms = machine.vms hm.status = machine.status hm.msg = machine.msg hm.sqlversion = machine.sqlVersion hm.vsinstalled = machine.vsInstalled hm.save() except hmobj.DoesNotExist: hmobj.objects.create(machine_name=machine.machineName, owner=machine.owner, ip=machine.ip, installedupdate=machine.installedUpdate, os=machine.osName, osversion=machine.osVersion, oslang=machine.osLang, rebootrequired=machine.rebootRequired, lastscantime=machine.scancompletetime, vms=machine.vms, status=machine.status, msg=machine.msg, sqlversion=machine.sqlVersion, vsinstalled=machine.vsInstalled) except Exception as e: print('DB.save error: host not found or save failed') LogHelper.append( 'DB.save error: host {0} not found or save failed'.format( machine.machineName)) elif type == 'vm': if location == 'sh': vmobj = SHVirtualMachine hm = SHHost.objects.get(machine_name=machine.hostName) elif location == 'red': vmobj = REDVirtualMachine hm = REDHost.objects.get(machine_name=machine.hostName) try: vm = vmobj.objects.get(vmid=machine.vmid) vm.ip = machine.ip vm.installedupdate = machine.installedUpdate vm.os = machine.osName vm.osversion = machine.osVersion vm.oslang = machine.osLang vm.rebootrequired = machine.rebootRequired vm.fullyqualifieddomainname = machine.fullyQualifiedDomainName vm.domainname = machine.domainName vm.lastscantime = machine.scancompletetime vm.loc_host = hm vm.status = machine.status vm.msg = machine.msg vm.sqlversion = machine.sqlVersion vm.vsinstalled = machine.vsInstalled vm.save() except vmobj.DoesNotExist: vmobj.objects.create( machine_name=machine.machineName, vmid=machine.vmid, ip=machine.ip, installedupdate=machine.installedUpdate, os=machine.osName, osversion=machine.osVersion, oslang=machine.osLang, rebootrequired=machine.rebootRequired, fullyqualifieddomainname=machine.fullyQualifiedDomainName, domainname=machine.domainName, lastscantime=machine.scancompletetime, loc_host=hm, status=machine.status, msg=machine.msg, sqlversion=machine.sqlVersion, vsinstalled=machine.vsInstalled) except Exception as e: print(str(e)) LogHelper.append('update or create vm object failed') elif type == 'azm': try: azm = AzureVirtualMachine.objects.get( machine_name=machine.machineName) azm.ip = machine.ip azm.installedupdate = machine.installedUpdate azm.os = machine.osName azm.osversion = machine.osVersion azm.oslang = machine.osLang azm.rebootrequired = machine.rebootRequired azm.lastscantime = machine.scancompletetime azm.status = machine.status azm.msg = machine.msg azm.resourceid = machine.resourceID azm.location = machine.location azm.resourcename = machine.resourceName azm.resourcegroupname = machine.resourceGroupName azm.role = machine.role azm.owner = machine.owner azm.save() except AzureVirtualMachine.DoesNotExist: AzureVirtualMachine.objects.create( machine_name=machine.machineName, ip=machine.ip, installedupdate=machine.installedUpdate, os=machine.osName, osversion=machine.osVersion, oslang=machine.osLang, rebootrequired=machine.rebootRequired, lastscantime=machine.scancompletetime, status=machine.status, msg=machine.msg, resourceid=machine.resourceID, location=machine.location, resourcename=machine.resourceName, resourcegroupname=machine.resourceGroupName, role=machine.role, owner=machine.owner) except Exception as e: print('DB.save error: Azure Machine not found or save failed') LogHelper.append( 'DB.save error: Azure Machine not found or save failed')
def get_sqlversion(machinename, username, password): rootnamespace = r'root\Microsoft\SqlServer' relativenamespace = None try: namespaces = WMIHelper.enum_namespace(machinename, username, password, rootnamespace) print(namespaces) for namespace in namespaces: print(namespace.Name) name_check = re.match(r'ComputerManagement[\d\d]?', namespace.Name) print(name_check) if name_check is None: pass else: relativenamespace = namespace.Name fullnamespace = rootnamespace + '\\' + namespace.Name print(fullnamespace) wql = "SELECT PropertyStrValue FROM SqlServiceAdvancedProperty WHERE PropertyName='FILEVERSION' AND ServiceName='MSSQLSERVER'" results = WMIHelper.executeWMIQuery( machinename, username, password, fullnamespace, wql) for result in results: patch_version = result.PropertyStrValue return patch_version except Exception as e: print("get wmi sqlversion failed") LogHelper.append( "Get wmi sqlversion failed {0} with {1}:{2}".format( machinename, username, password)) pass try: rootreg = r'SOFTWARE\Microsoft\Microsoft SQL Server' instancenamekey = r'SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL' reginstance = WMIHelper.enumRegValue(machinename, username, password, instancenamekey) for key in reginstance: instancekey = reginstance[key] print(instancekey) relativekey = instancekey + r'\Setup' print(relativekey) regvalue = 'PatchLevel' """ if relativenamespace == 'ComputerManagement10': relativekey = r'\100\Tools\Setup' elif relativenamespace == 'ComputerManagement11': relativekey = r'\110\Tools\Setup' elif relativenamespace == 'ComputerManagement12': relativekey = r'\120\Tools\Setup' elif relativenamespace == 'ComputerManagement13': relativekey = r'\130\Tools\Setup' elif relativenamespace == 'ComputerManagement14': relativekey = r'\140\Tools\Setup' """ regkey = rootreg + '\\' + relativekey patch_version = WMIHelper.getRegValue(machinename, username, password, regkey, regvalue) return patch_version except Exception as e: print("get reg sqlversion failed") LogHelper.append( "Get reg sqlversion failed {0} with {1}:{2}".format( machinename, username, password))
def testconnection(self): log = CMDHelper.testconnection(self.ip) LogHelper.append("vm test ip connection {0}:{1} is {2}".format( self.machineName, self.ip, log))