Beispiel #1
0
def verifyHost(hostIPAddr = None,
               password = None):
    userName = "******"
    try:
        conn = pywbem.WBEMConnection('http://'+hostIPAddr, (userName, password))
    except:
        raise xenrt.XRTFailure("Authentication of host failed with Password %s" % (password))
Beispiel #2
0
def add_vnx(spa_ip,
            spb_ip,
            array_user,
            array_pass,
            ecom_ip,
            ecom_user="******",
            ecom_pass="******"):

    ecom_url = "https://%s:5989" % ecom_ip
    ecom_conn = pywbem.WBEMConnection(ecom_url, (ecom_user, ecom_pass),
                                      default_namespace="/root/emc")
    ers = ecom_conn.EnumerateInstanceNames("EMC_SystemRegistrationService")
    o = ecom_conn.InvokeMethod("EMCAddSystem",
                               ers[0],
                               ArrayType=pywbem.Uint16(1),
                               Addresses=[spa_ip, spb_ip],
                               Types=[pywbem.Uint16(2),
                                      pywbem.Uint16(2)],
                               User=array_user,
                               Password=array_pass)

    results = [
        "Success", "Not Supported", "Unknown", "Timeout", "Failed",
        "Inavlid Parameter", "In Use", "Existing"
    ]
    print "Execution Ouput:"
    print o
    print "Result: %s" % results[o[0]]
def main():
    exitval = {
            "OK" : 0,
        "WARNING" : 1,
        "CRITICAL" : 2,
        "UNKNOWN" : 3
       }
    vm_namespace = "vmware/esxv2"
    client = pywbem.WBEMConnection(url, auth, vm_namespace)
    vms = client.EnumerateInstances('VMWARE_StoragePool')
    count = 0
    metrics = metric
    if not metric:
        metrics = "bytes"
    else:
        metrics = metric
    for vm in vms:
        vmname = vm['ElementName']
        total = DmetricCalc(vm['TotalManagedSpace'], metrics)
        remaining = DmetricCalc(vm['RemainingManagedSpace'], metrics)
        used = total - remaining
        percent_used = (used * 100) / total
        if dstore:
            dsmatch = "^"+dstore+"$"
            if re.search(dsmatch, vmname):
                rval = threshold(percent_used)
                count += 1
                print rval, dstore, str(remaining)+metrics+" Avail",str(percent_used)+"% used "+ "|avail="+str(remaining)
                sys.exit(exitval[rval])
    if count == 0:
        print "DataStore %s Does Not Exists on %s"  % ( dstore, url )
def ecom_connect(ecom_ip, ecom_user, ecom_pass, default_namespace="/root/emc"):
    """ returns a connection to the ecom server """
    ecom_url = "https://%s:5989" % ecom_ip

    return pywbem.WBEMConnection(ecom_url, (ecom_user, ecom_pass),
                                 default_namespace="/root/emc",
                                 no_verification=True)
def main():
    vm_namespace = "vmware/esxv2"
    client = pywbem.WBEMConnection(url, auth, vm_namespace)
    vms = client.EnumerateInstances('VMWARE_StoragePool')
    vispc = client.EnumerateInstances(
        'VMWARE_VirtualInitiatorSCSIProtocolController')
    print "Available DataStores on %s\n" % (url)
    count = 0
    for vm in vms:
        vmname = vm['ElementName']
        vsname = "^\[" + vmname + "\]"
        total = vm['TotalManagedSpace'] / 1024 / 1024 / 1024
        remaining = vm['RemainingManagedSpace'] / 1024 / 1024 / 1024
        used = total - remaining
        percent_used = (used * 100) / total
        if dstore:
            dsmatch = "^" + dstore + "$"
            if re.search(dsmatch, vmname):
                printDstore(total, remaining, used, percent_used, vmname,
                            vispc)
                count += 1
                sys.exit(0)
        elif not dstore:
            printDstore(total, remaining, used, percent_used, vmname, vispc)
            count += 1
    if count == 0:
        print "DataStore %s Does Not Exists on %s" % (dstore, url)
Beispiel #6
0
def main():
    par_namespace = "root/tpd"
    client = pywbem.WBEMConnection(options.url, options.auth, par_namespace)
    stats = None
    if options.volume:
        stats = client.EnumerateInstances('TPD_VolumeStatisticalData')
    elif options.port:
        stats = client.EnumerateInstances('TPD_PortStatisticalData')
    elif options.disk:
        stats = client.EnumerateInstances('TPD_DiskStatisticalData')
    else:
        print "Pass -h for help with this script"
        sys.exit(0)

    count = 0
    nstats = []
    for stat in stats:
        if options.volume or options.port or options.disk:
            if options.search:
                if re.search(options.search,
                             stat["ElementName"].split(" ")[1]):
                    nstats.append(storeNagiosValues(nstats, stat))
            else:
                nstats.append(storeNagiosValues(nstats, stat))
        else:
            print "Pass -h for help with this script"
            sys.exit(0)

    pstats = re.sub(r"u\'|\"|\,|\'|\(|\)|\[|\]", "", str(nstats))
    if len(pstats) > 0:
        print "OK|" + pstats
        sys.exit(exitval["OK"])
    else:
        print "Critical, no stats found"
        sys.exit(exitval["CRITICAL"])
Beispiel #7
0
class BVTTest(TestSetUp):

    def __init__(self, Ip, userName, password):
        TestSetUp.__init__(self, Ip, userName, password)
            
    def getCurrentState(self, vm_ref):
        vm_inst = self.conn.GetInstance(vm_ref)
        return vm_inst['status']

    def TestCIMAuthentication (self):
        self.TestBegin()
        result = 1
        print 'Enumerate with a bad user'
        try:
            localconn = pywbem.WBEMConnection('http://'+ self.IPAddress, ("badusername", self.Password))
            vsms = localconn.EnumerateInstanceNames("Xen_VirtualSystemManagementService")
            print 'SECURITY ERROR: Authentication worked with bad user - found %d VSMS' % len(vsms)
            result = 0
        except Exception, e:
            print 'SUCCESS: Got "%s" exception with bad user' % str(e)
        try:
            localconn = pywbem.WBEMConnection('http://'+ self.IPAddress, (self.UserName, "badpassword"))
            vsms = localconn.EnumerateInstanceNames("Xen_VirtualSystemManagementService")
            print 'SECURITY ERROR: Authentication worked with bad password - found %d VSMS' % len(vsms)
            result = 0
        except Exception, e:
            print 'SUCCESS: Got "%s" exception with bad password' % str(e)
Beispiel #8
0
 def get_wbem_connection(self): 
     """Return a wbem connection to ZOS_SERVER"""
     #if not args:
         #args = ('https://localhost', ('pegasus', 'novell'))
     #conn = pywbem.WBEMConnection(*args)
     conn = pywbem.WBEMConnection('https://localhost', ('pegasus', 'novell'))
     conn.default_namespace = 'root/cimv2'
     return conn
Beispiel #9
0
def get_symm_conn(debug):
    """Return a connection to SMI-S provider
    """
    conn = pywbem.WBEMConnection(SMIS_IP + ":" + SMIS_PORT,
                                 (SMIS_USER, SMIS_PASS),
                                 default_namespace='root/emc',
                                 no_verification=True)
    return conn
def hp_wbem_connect(hp_user, hp_password, hp_ip, hp_port):
	try:
		wbem_url = "https://{0}:{1}".format(hp_ip, hp_port)
		wbem_connect = pywbem.WBEMConnection(wbem_url, (hp_user, hp_password), default_namespace = "root/tpd", no_verification=True, timeout=50)
		hp_logger.info("WBEM Connection Established Successfully")
		return wbem_connect 
	except Exception as oops:
		hp_logger.error("WBEM Connection Error Occurs".format(oops))
		sys.exit("1000")
def ecom_connect(ecom_ip, ecom_user, ecom_pass, default_namespace="/root/emc"):
    """ returns a connection to the ecom server """
    ecom_url = "http://%s:5988" % ecom_ip

    logger = logging.getLogger('discovery')
    logger.info("Building WBEM Connection to %s" % ecom_url)

    return pywbem.WBEMConnection(ecom_url, (ecom_user, ecom_pass),
                                 default_namespace="/root/emc")
Beispiel #12
0
    def __init__(self, options=None):
        # Borgness
        self.__dict__ = WBEMConn._shared_state

        if options:
            self.conn = pywbem.WBEMConnection(
                    options.url,
                    (options.user, options.password),
                    default_namespace = options.namespace)
Beispiel #13
0
 def get_local_connection(self):
     'Sets up a connection to a WBEM server.'
     print("Testing Intel WBEM requires admin permissions.")
     username = input("Admin username: ")
     password = getpass.getpass()
     
     return pywbem.WBEMConnection('http://' + self.WBEM_HOST, 
         creds=(username, password),
         default_namespace=self.namespace)
Beispiel #14
0
 def _WBEMConnFromOptions(self, options=None):
     if options is None:
         parser = OptionParser()
         getWBEMConnParserOptions(parser)
         options, args = parser.parse_args()
     proto = options.secure and 'https' or 'http'
     url = '%s://%s:%s' % (proto, options.host, options.port)
     wconn = pywbem.WBEMConnection(url, (options.user, options.password),
             default_namespace=options.namespace)
     return wconn
def wbem_establish_connection(hostname, user, password):
    try:
        port_string = ':5989'
        hostname = 'https://' + hostname + port_string
        conn = pywbem.WBEMConnection(hostname, (user, password),
                                     default_namespace='solarflare/cimv2',
                                     no_verification=True)
        return conn
    except ConnectionError:
        fatal('Connection to host %s failed', hostname)
Beispiel #16
0
def cim():
    name = request.form['name']
    wbem = pywbem.WBEMConnection(name)
    os = wbem.EnumerateInstances('CIM_OperatingSystem')[0]['Version'].split()
    os = os[0] + '\n' + os[1]
    interface = ''
    interfaces = wbem.EnumerateInstances('CIM_IPProtocolEndpoint')
    for i in interfaces:
        interface += 'Name=' + i['Name'] + '\nIPv4Address=' + i[
            'IPv4Address'] + '\n\n'
    return render_template('index.html', os=os, interface=interface)
Beispiel #17
0
def ecom_connect(ecom_ip, ecom_user, ecom_pass, default_namespace="root/emc",no_verification=True):
    """ returns a connection to the ecom server """
    #ecom_url = "https://%s:5989" % ecom_ip
    ecom_url = "https://172.16.1.171:5989"

    logger = logging.getLogger('discovery')
    logger.info("Building WBEM Connection to %s" % ecom_url)

    return pywbem.WBEMConnection(ecom_url, (ecom_user, ecom_pass),
                                 #default_namespace="interop",no_verification=True)
                                 default_namespace="root/emc",no_verification=True)
Beispiel #18
0
 def TestCIMAuthentication (self):
     self.TestBegin()
     result = 1
     print 'Enumerate with a bad user'
     try:
         localconn = pywbem.WBEMConnection('http://'+ self.IPAddress, ("badusername", self.Password))
         vsms = localconn.EnumerateInstanceNames("Xen_VirtualSystemManagementService")
         print 'SECURITY ERROR: Authentication worked with bad user - found %d VSMS' % len(vsms)
         result = 0
     except Exception, e:
         print 'SUCCESS: Got "%s" exception with bad user' % str(e)
Beispiel #19
0
def WbemConnection(cgi_url):
    """For the moment, it cannot connect to https:
    #https://github.com/Napsty/check_esxi_hardware/issues/7 """
    creden = lib_credentials.GetCredentials("WBEM", cgi_url)

    #if creden == ('', ''):
    #    raise Exception("WbemConnection: No credentials for %s" % cgi_url)

    logging.debug("WbemConnection creden=%s", str(creden))
    # Beware: If username/password is wrong, it will only be detected at the first data access.
    conn = pywbem.WBEMConnection(cgi_url, creden)
    return conn
def get_ecom_connection():
    #     conn = pywbem.WBEMConnection('https://10.108.246.160', ('admin', '#1Password'),
    #                                      default_namespace='root/emc')
    #     conn = pywbem.WBEMConnection('https://10.108.246.206', ('admin', '#1Password'),
    #                                      default_namespace='root/emc')
    conn = pywbem.WBEMConnection('http://10.108.246.202',
                                 ('admin', '#1Password'),
                                 default_namespace='root/emc')
    if conn is None:
        LOG.error(_("Cannot connect to ECOM server"))
        raise
    return conn
Beispiel #21
0
def systems(url, username, password):
    # We will support interop so that we don't have to specify namespace
    rc = 4

    try:
        try:
            conn = pywbem.WBEMConnection(url, (username, password),
                                         DEFAULT_NAMESPACE,
                                         no_verification=True)
        except Exception as ei:
            # Some versions of pywbem don't support the parameter
            # 'no_verification'
            if 'no_verification' in str(ei):
                conn = pywbem.WBEMConnection(url, (username, password),
                                             DEFAULT_NAMESPACE)
            else:
                raise

        if conn:
            rps = get_cim_rps(conn)

            if rps:
                cim_systems = conn.Associators(
                    rps.path,
                    ResultClass='CIM_ComputerSystem',
                    AssocClass='CIM_ElementConformsToProfile')
                if len(cim_systems):
                    print('Found %d system(s)' % (len(cim_systems)))
                    rc = 0
                else:
                    print('No systems found!')
                    rc = 1
            else:
                rc = 3
    except Exception as e:
        if 'Unauthorized' in str(e):
            rc = 2
        else:
            print('Exception: ', str(e))
    return rc
Beispiel #22
0
    def connection(self):
        if self._connection is None:
            url = "http://{ip}:{port}".format(ip=self.ip, port=self.port)
            self._connection = pywbem.WBEMConnection(
                url, creds=(self.user, self.password),
                default_namespace=EMC_ROOT)
            if self._connection is None:
                msg = ("Cannot connect to EMC ECOM server at '{url}', check "
                       "your configuration and connectivity.".format(url=url))
                LOG.error(msg)
                raise BackendNotAvailable(msg)

        return self._connection
Beispiel #23
0
def WbemConnection(cgiUrl):
    try:
        creden = lib_credentials.GetCredentials("WBEM", cgiUrl)

        # ATTENTION: Si probleme de connection, on ne le voit pas ici mais au moment du veritable acces.
        conn = pywbem.WBEMConnection(cgiUrl, creden)
    except Exception:
        exc = sys.exc_info()[1]
        lib_common.ErrorMessageHtml("Connecting to :" + cgiUrl + " Caught:" +
                                    str(exc) + "<br>")

    # TestCookie(url)
    return conn
Beispiel #24
0
def generate_class_documentation(class_name,
                                 server,
                                 user,
                                 passwd,
                                 name_space="root/cimv2"):
    conn = pywbem.WBEMConnection('http://' + server + ':5988', (user, passwd))
    params = {
        'LocalOnly': False,
        'IncludeQualifiers': True,
        'IncludeClassOrigin': True
    }
    class_obj = conn.GetClass(class_name, **params)
    doc = __generate_class_documentation(conn, class_obj)
    doc = doc.replace('<NAMESPACE>', name_space)
    return doc
Beispiel #25
0
def TestPYWBEM():

	conn = pywbem.WBEMConnection("http://192.168.1.88", ("pegasus", "toto"))

	with_code = False
	if  with_code:
		cl = conn.GetClass("LMI_ServiceAffectsIdentity")
		(provider, registration) = pywbem.cim_provider2.codegen(cl)

		print provider
		print registration
		
	svc = conn.EnumerateInstances("LMI_ServiceAffectsIdentity")

	print svc[0]
Beispiel #26
0
def WbemConnection(cgiUrl):
    try:
        # For the moment, it cannot connect to https:
        # https://github.com/Napsty/check_esxi_hardware/issues/7
        creden = lib_credentials.GetCredentials("WBEM", cgiUrl)

        DEBUG("WbemConnection creden=%s", str(creden))
        # Beware: If username/password is wrong, it will only be detected at the first data access.
        conn = pywbem.WBEMConnection(cgiUrl, creden)
    except Exception:
        exc = sys.exc_info()[1]
        lib_common.ErrorMessageHtml("Connecting to :" + cgiUrl + " Caught:" +
                                    str(exc) + "<br>")

    # TestCookie(url)
    return conn
Beispiel #27
0
    def Connect(self, namespace='root/ibm', printing=False):

        import pywbem

        server_uri = 'https://' + self.ip.rstrip()

        try:
            conn = pywbem.WBEMConnection(server_uri,
                                         (self.login, self.password),
                                         namespace,
                                         no_verification=True)
        except:
            print('Unexpected exception in \"ZabbixSender(' +
                  nd_parameters['zabbix_server'] + ').send(packet)\": ' +
                  str(sys.exc_info()))

        return conn
Beispiel #28
0
def main():
    vm_namespace = "vmware/esxv2"
    client = pywbem.WBEMConnection(url, auth, vm_namespace)
    vms = client.EnumerateInstances('VMWARE_VMComputerSystem')
    count = 0

    for vm in vms:
        if name:
            dsmatch = "^" + name + "$"
            if re.search(dsmatch, vm['ElementName']):
                printVminfo(vm)
                count += 1
                sys.exit(0)
        elif not name:
            printVminfo(vm)
            count += 1
    if count == 0:
        print "VirtualMachine %s Does Not Exists on %s" % (name, url)
Beispiel #29
0
def WbemConnection(cgiUrl):
    try:
        # TODO Stocker ca dans les cookies.
        #if cgiUrl == "http://127.0.0.1":
        #    creden = ('', '')
        #elif cgiUrl == "http://192.168.1.88":
        #    creden = ('pegasus', 'toto')
        #else:
        #    creden = ('', '')
        creden = lib_credentials.GetCredentials("WBEM", cgiUrl)

        # ATTENTION: Si probleme de connection, on ne le voit pas ici mais
        # au moment du veritable acces.
        conn = pywbem.WBEMConnection(cgiUrl, creden)
    except Exception:
        exc = sys.exc_info()[1]

        ThrowException("cgiUrl=" + cgiUrl + " Caught:" + str(exc) + "<br>")

    # TestCookie(url)
    return conn
Beispiel #30
0
def __generate_method_signature(method):
    #    inParams = [ p for p in method.parameters.values() if \
    #            'in' in p.qualifiers and p.qualifiers['in'].value ]
    #    outParams = [ p for p in method.parameters.values() if \
    #            'out' in p.qualifiers and p.qualifiers['out'].value ]
    in_params = ''
    out_params = ''
    conn = pywbem.WBEMConnection('http://localhost', ('', ''))

    for p in method.parameters.values():
        if 'out' in p.qualifiers and p.qualifiers['out'].value != False:
            if 'in' in p.qualifiers and p.qualifiers['in'].value != False:
                out_params += 'in out %s %s, ' % (__get_data_type(p), p.name)
            else:
                out_params += 'out %s %s, ' % (__get_data_type(p), p.name)
        else:
            in_params += 'in %s %s, ' % (__get_data_type(p), p.name)
    params = in_params + out_params
    params = params.rstrip(', ')
    sig = '%s %s ( %s )' % (method.return_type, method.name, params)
    return sig