def get_wmi_info(hostname, username, password, classname): con = wmi.WmiClientWrapper(username=username, host=hostname, password=password) res = None res = con.query("SELECT * FROM {0}".format(classname)) return res
def perform_shutdown(self): if self.typ == 'linux': try: ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) key = paramiko.RSAKey.from_private_key_file(cfg_data['general']['private_rsa_key']) ssh.connect(self.host, username=self.user, pkey=key) ssh.exec_command('; '.join(self.cmds)) ssh.close() self.turned_off = True notify(0, 'host_turned_off', 'Host {} has been turned off!'.format(self.host), 'Host {} has been powered down due to UPS\'s current runtime.'.format(self.host)) log(0, 'Host {} has been powered down due to UPS\'s current runtime'.format(self.host)) except Exception: notify(1, 'host_turned_off', 'Unable to shutdown {} host!'.format(self.host), 'Unable to shutdown {} host due to unexpected error! Please see logs for more info.'.format(self.host)) log(1, 'Unable to shutdown {} host due to unexpected error! Reason\n{}'.format(self.host, traceback.print_exc())) if self.typ == 'windows': try: con = wmi.WmiClientWrapper(username=self.user, password=self.password, host=self.host) for cmd in self.cmds: con.Win32_Process.Create(CommandLine=cmd) con.close() self.turned_off = True notify(0, 'host_turned_off', 'Host {} has been turned off!'.format(self.host), 'Host {} has been powered down due to UPS\'s current runtime.'.format(self.host)) log(0, 'Host {} has been powered down due to UPS\'s current runtime'.format(self.host)) except Exception: notify(1, 'host_turned_off', 'Unable to shutdown {} host!'.format(self.host), 'Unable to shutdown {} host due to unexpected error! Please see logs for more info.'.format(self.host)) log(1, 'Unable to shutdown {} host due to unexpected error! Reason\n{}'.format(self.host, traceback.print_exc())) self.turned_off = True
def __init__(self, host, username, password, wql, dstDir): self.host = host self.username = username self.password = password self.wql = wql self.dstDir = dstDir self.wmic = wmi.WmiClientWrapper(username=username, password=password, host=host)
def auth(ip, user, password, secure, custom_port): # Authentication to WMI query service wmic = wmi.WmiClientWrapper(\ username = user,\ password = password,\ host = ip) # Authentication to WinRM (to execute cmd commands) if secure: protocol = "https" port = HTTPS_PORT print("\nUsing HTTPS") else: protocol = "http" port = HTTP_PORT print("\nWARNING: using HTTP, connection not secure") if custom_port: port = custom_port return winrm.Session(\ protocol + "://" + ip + ":" + port + "/wsman",\ auth = (user, password)),\ wmic
def mlcacheOn(hosts): try: wmic = wmi.WmiClientWrapper(username="******",password="******",host=hosts) output = wmic.query("SELECT Caption FROM win32_process WHERE Name='MLCache.EXE'") except: output="error" return output
def wmi_test(usr, pwd, dom, dst): output = None dom_usr = dom + "/" + usr wmic = wmi.WmiClientWrapper(username=dom_usr, password=pwd, host=dst) try: output = wmic.query("SELECT * FROM Win32_Processor") except: ouptut = False if output: return (True) else: return (False)
def get_wmi_info_with_fields(hostname, username, password, classname, fields): con = wmi.WmiClientWrapper(username=username, host=hostname, password=password) res = None if isinstance(fields, list) and len(fields) == 0: res = con.query("SELECT * FROM {0}".format(classname)) elif isinstance(fields, list) and len(fields) > 0: res = con.query("SELECT {0} FROM {1}".format(", ".join(fields), classname)) elif not isinstance(fields, list): raise TypeError("fields must be a type of list") return res
def test_delimiter_in_setup(self): expected_delimiter = "FOOBAR" wmic = wmi.WmiClientWrapper( username="******", password="******", host="192.168.1.173", delimiter=expected_delimiter, ) output = " ".join(wmic._setup_params()) self.assertIn(expected_delimiter, output)
def transport_wmi_metric_to_kafka_with_fields(hostname, username, password, classname, fields): p = Producer({'bootstrap.servers': BROKER_CONF}) con = wmi.WmiClientWrapper(username=username, host=hostname, password=password) def delivery_report(err, msg): if err is not None: raise Exception("Message delivery failed : {0}".format(err)) else: pass timestamp = datetime.now().replace(tzinfo=timezone.utc).timestamp() res = None if isinstance(fields, list) and len(fields) == 0: res = con.query("SELECT * FROM {0}".format(classname)) elif isinstance(fields, list) and len(fields) > 0: res = con.query("SELECT {0} FROM {1}".format(", ".join(fields), classname)) elif not isinstance(fields, list): raise TypeError("fields must be a type of list") if res is None: raise Exception("Failed to collect remotely in {0}".format(hostname)) elif isinstance(res, dict): p.produce(KAFKA_TOPIC_CONF, json.dumps(res).encode('utf-8'), callback=delivery_report, timestamp=timestamp) p.flush() elif isinstance(res, list): # the returned-value is usually a list. if len(res) >= 1 and isinstance(res[0], dict): res = res[0] p.produce(KAFKA_TOPIC_CONF, json.dumps(res).encode('utf-8'), callback=delivery_report, timestamp=timestamp) p.flush() elif len(res) == 0: raise Exception("Detect empty list {0} - {1}".format( hostname, classname)) else: raise Exception("Unknown Exception : {0} - {1}".format( hostname, classname)) pass # TODO: (gbkim) to check the result in the flower, you should return the windows response return res
def get_wmi_data(EM_host, username, password): try: # Connect to the Host in the correct WMI Namespace wmic = wmi.WmiClientWrapper( username=username, password=password, host=EM_host, namespace='//./root/veeamEM' ) output = wmic.query('Select * FROM License') return output except Exception as e: print("Error calling \"get_wmi_data\"... Exception {} --- Verify login or password !".format(e)) sys.exit(3)
def is_accessible(self): if self.typ == 'linux': try: ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) key = paramiko.RSAKey.from_private_key_file(cfg_data['general']['private_rsa_key']) ssh.connect(self.host, username=self.user, pkey=key) ssh.close() return True except Exception: notify(1, 'host_connection_fail', 'Unable to access {} host!'.format(self.host), 'Unable to access {} host via SSH! Please check to make sure the host is reachable from the host running HawkUPS system. Please check logs for more info.'.format(self.host)) log(1, 'Unable to access {} host via SSH! Please check to make sure the host is reachable from the host running HawkUPS system! Reason:\n{}'.format(self.host, traceback.print_exc())) return False elif self.typ == 'windows': try: wmi.WmiClientWrapper(username=self.user, password=self.password, host=self.host) return True except Exception: notify(1, 'host_connection_fail', 'Unable to access {} host!'.format(self.host), 'Unable to access {} host via WMI! Please check to make sure the host is reachable from the host running HawkUPS system. Please check logs for more info.'.format(self.host)) log(1, 'Unable to access {} host via WMI! Please check to make sure the host is reachable from the host running HawkUPS system! Reason:\n{}'.format(self.host, traceback.print_exc())) return False else: log(2, 'Unrecognized host type for {}!'.format(self.host))
wmi_imported = True except ImportError: wmi_imported = False ################################################################################ # TODO: Just a reminder that WMI can run on Linux, in a certain extent. # https://pypi.python.org/pypi/wmi-client-wrapper if False: if lib_util.isPlatformLinux: import wmi_client_wrapper as wmilnx wmic = wmilnx.WmiClientWrapper( username="******", password="******", host="192.168.1.149", ) output = wmic.query("SELECT * FROM Win32_Processor") ################################################################################ def BuildWmiMoniker(hostnameWmi, namespac="", classNam=""): return "\\\\" + hostnameWmi + "\\" + namespac + ":" + classNam + "." # namespaces_wmi.py def WmiAllNamespacesUrl(hostnameWmi): wmiMoniker = BuildWmiMoniker(hostnameWmi)
def test_object_creation(self): wmic = wmi.WmiClientWrapper(username="******", password="******", host="192.168.1.173")
def test_object_creation_raises_without_host(self): with self.assertRaises(Exception): wmic = wmi.WmiClientWrapper(username="******", password="******")
def test_object_creation_raises_without_username(self): with self.assertRaises(Exception): wmic = wmi.WmiClientWrapper()
def setUp(self): self.wmic = wmi.WmiClientWrapper( username="******", password="******", host="127.0.0.2", )
def _get_client(self, host, username, password): client = wmi.WmiClientWrapper(username=username, password=password, host=host) return client
import wmi_client_wrapper as wmi wmic = wmi.WmiClientWrapper(username="******", password="******", host="192.168.200.247:3766")
# -*- coding: utf-8 -*- import wmi_client_wrapper as wmi import sys import json # wmic = wmi.WmiClientWrapper( # username="******", # password="******", # host="191.168.3.158" # ) script, cip, cuser, cpass = sys.argv wmic = wmi.WmiClientWrapper(username=cuser, password=cpass, host=cip) # 通过wmi获取不同的指标,获取方法类似 Win32_Processor = wmic.query("SELECT * FROM Win32_Processor") Win32_Battery = wmic.query("SELECT * FROM Win32_Battery") Win32_PortableBattery = wmic.query("SELECT * FROM Win32_PortableBattery") outjson = {} # 放数到输出对象中 outjson["Win32_Processor"] = Win32_Processor outjson["Win32_Battery"] = Win32_Battery outjson["Win32_PortableBattery"] = Win32_PortableBattery # 将结果转换成Json并输出 pj = json.dumps(outjson) print(pj)