def delete(self, name=None, uri=None, api=None, headers=None):
     if api:
         headers = self.fusion_client._set_req_api_version(api=api)
     elif not headers:
         headers = self.fusion_client._headers.copy()
     if uri:
         uri = 'https://%s%s' % (self.fusion_client._host, uri)
     elif name:
         param = '?&filter="\'name\' == \'%s\'"' % (name)
         response = self.get(api=api, headers=headers, param=param)
         if response['count'] == 0:
             logger._log('Server Profile Template %s does not exist' %
                         (name),
                         level='WARN')
             return
         elif response['count'] > 1:
             msg = "Filter %s returned more than one result" % (name)
             raise Exception(msg)
         else:
             uri = 'https://%s%s' % (self.fusion_client._host,
                                     response['members'][0]['uri'])
     else:
         # deletes all server profile templates
         uri = 'https://%s/rest/server-profile-templates' % self.fusion_client._host
     response = self.fusion_client.delete(uri=uri, headers=headers)
     return response
 def delete(self, name=None, uri=None, param='', api=None, headers=None):
     if api:
         headers = self.fusion_client._set_req_api_version(api=api)
     elif not headers:
         headers = self.fusion_client._headers
     if uri:
         uri = 'https://%s%s%s' % (self.fusion_client._host, uri, param)
     elif name:
         param = '?&filter="\'name\' eq \'%s\'"' % (name)
         response = self.get(api=api, headers=headers, param=param)
         if response['count'] == 0:
             logger._log('Power Device %s does not exist' % (name),
                         level='WARN')
             return
         elif response['count'] > 1:
             msg = "Filter %s returned more than one result" % (name)
             raise Exception(msg)
         else:
             uri = 'https://%s%s%s' % (self.fusion_client._host,
                                       response['members'][0]['uri'], param)
     else:
         # deletes all power devices
         uri = 'https://%s/rest/power-devices' % (self.fusion_client._host,
                                                  uri)
     response = self.fusion_client.delete(uri=uri, headers=headers)
     return response
    def delete(self, name=None, uri=None, param='', api=None, headers=None):
        '''
        param: ?suppressDeviceUpdates=true only remove the volume from Oneview only.
               ?suppressDeviceUpdates=false remove the volume from Oneview and StorageSystem.
        '''

        if api:
            headers = self.fusion_client._set_req_api_version(api=api)
        elif not headers:
            headers = self.fusion_client._headers.copy()

        if uri:
            uri = 'https://%s%s%s' % (self.fusion_client._host, uri, param)
        elif name:
            param = '?&filter="\'name\' == \'%s\'"' % (name)
            response = self.get(api=api, headers=headers, param=param)
            if response['count'] == 0:
                logger._log('Storage Volume %s does not exist' % (name),
                            level='WARN')
                return
            elif response['count'] > 1:
                msg = "Filter %s returned more than one result" % (name)
                raise Exception(msg)
            else:
                uri = 'https://%s%s%s' % (self.fusion_client._host,
                                          response['members'][0]['uri'], param)
        response = self.fusion_client.delete(uri=uri, headers=headers)
        return response
 def delete(self, name=None, uri=None, api=None, headers=None, param=''):
     """Removes an Rackmanager from the appliance based on name OR uri
         [Arguments]
         name: a dictionary containing request body elements
         uri: the uri of the resource to remove.
         param: you can use param=?force="true" to force remove a rackmanager
         [Example]
         ${resp} = Fusion Api Remove Rackmanager | <name> | <uri> | <param> | <api> | <headers>
     """
     if api:
         headers = self.fusion_client._set_req_api_version(api=api)
     elif not headers:
         headers = self.fusion_client._headers.copy()
     if uri:
         uri = 'https://%s%s%s' % (self.fusion_client._host, uri, param)
     elif name:
         param2 = '?&filter="\'name\' == \'%s\'"' % (name)
         response = self.get(api=api, headers=headers, param=param2)
         if response['count'] == 0:
             logger._log('Rackmanager %s does not exist' % (name),
                         level='WARN')
             return
         elif response['count'] > 1:
             msg = "Filter %s returned more than one result" % (name)
             raise Exception(msg)
         else:
             uri = 'https://%s%s%s' % (self.fusion_client._host,
                                       response['members'][0]['uri'], param)
     response = self.fusion_client.delete(uri=uri, headers=headers)
     return response
示例#5
0
 def add(self, localfile, api=None, headers=None):
     self.i3s_client._headers = {}
     self.i3s_client._headers = self.i3s_client.set_def_api_version()
     if api:
         headers = self.i3s_client._set_req_api_version(api=api)
     elif not headers:
         headers = self.i3s_client._headers
     uri = 'https://%s%s/' % (self.i3s_client._host,
                              common.uris.get('backup'))
     logger._log("Value in upload backup URI is" + str(uri))
     response = self.i3s_client.post_file(uri=uri,
                                          localfile=localfile,
                                          headers=self.i3s_client._headers)
     return response
示例#6
0
 def delete(self, name=None, uri=None, api=None, headers=None):
     if api:
         headers = self.fusion_client._set_req_api_version(api=api)
     elif not headers:
         headers = self.fusion_client._headers
     if uri:
         uri = 'https://%s%s' % (self.fusion_client._host, uri)
     elif name:
         param = '?&filter="\'name\' == \'%s\'"' % (name)
         response = self.get(api=api, headers=headers, param=param)
         if response['count'] == 0:
             logger._log('Zone %s does not exist' % (name), level='WARN')
             return
         else:
             uri = 'https://%s%s' % (self.fusion_client._host,
                                     response['members'][0]['uri'])
     response = self.fusion_client.delete(uri=uri, headers=headers)
     return response
示例#7
0
    def loginApic(self, host, cred):
        import json
        import requests

        base_url = 'https://%s/api/' % (host)
        json_credentials = json.dumps(cred)
        # log in to API
        login_url = base_url + 'aaaLogin.json'
        resp = requests.post(login_url, data=json_credentials, verify=False)
        logger._log_to_console_and_log_file("Resp is %s" % resp)
        logger._log('Response is %s' % (resp), level='DEBUG')
        auth = json.loads(resp.text)

        logger._log_to_console_and_log_file("Auth is %s" % auth)
        login_attributes = auth['imdata'][0]['aaaLogin']['attributes']
        logger._log_to_console_and_log_file("Auth is %s" % login_attributes)
        token = login_attributes['token']
        logger._log("Token is %s" % token)
        return token
    def __init__(self, supress_selenium_log=True):
        def convert_bool(s):
            if isinstance(s, types.BooleanType):
                return s
            elif isinstance(s, types.StringType) or isinstance(
                    s, types.UnicodeType):
                if s.lower() == 'true':
                    return True
                elif s.lower() == 'false':
                    return False
            raise Exception('Invalid value for boolean conversion: %s' % s)

        supress_selenium_log = convert_bool(supress_selenium_log)

        if supress_selenium_log is True:
            import logging
            from selenium.webdriver.remote.remote_connection import LOGGER
            LOGGER.setLevel(logging.WARNING)

        logger._log_to_console_and_log_file(
            "########################################################")
        if any(x in ['HTTP_PROXY', 'HTTPS_PROXY'] for x in os.environ):
            logger._log(
                "HTTP_PROXY or HTTPS_PROXY environment variables are set!",
                'WARN')
        logger._log_to_console_and_log_file("RoboGalaxyLibrary version %s" %
                                            __version__)
        logger._log_to_console_and_log_file("Developed by HPE ESSN QA Teams")
        logger._log_to_console_and_log_file(
            "Copyright 2015-2016 Hewlett Packard Enterprise Development LP")
        logger._log_to_console_and_log_file(
            "########################################################")
        logger._log_to_console_and_log_file("Robot Framework version %s" %
                                            robot_version.VERSION)
        logger._log_to_console_and_log_file("Selenium2Library version %s" %
                                            s2l.__version__)
        temp_dir = tempfile.gettempdir()
        sid = sha.new(repr(time.time())).hexdigest()
        internal_storage = temp_dir + "\\" + 'sess_' + sid

        for base in RoboGalaxyLibrary.__bases__:
            base.__init__(self)
示例#9
0
 def delete(self, name=None, uri=None, api=None, headers=None, param=''):
     if api:
         headers = self.i3s_client._set_req_api_version(api=api)
     elif not headers:
         headers = self.i3s_client._headers
     if uri:
         uri = 'https://%s%s%s' % (self.i3s_client._host, uri, param)
     elif name:
         param2 = '?&filter="\'name\' == \'%s\'"' % (name)
         response = self.get(api=api, headers=headers, param=param2)
         if response['count'] == 0:
             logger._log('Goldenimage %s does not exist' % (name),
                         level='WARN')
             return
         elif response['count'] > 1:
             msg = "Filter %s returned more than one result" % (name)
             raise Exception(msg)
         else:
             uri = 'https://%s%s%s' % (self.i3s_client._host,
                                       response['members'][0]['uri'], param)
     response = self.i3s_client.delete(uri=uri, headers=headers)
     return response
    def make_body(self, api, body, enc_grp_name):

        enc_grps = EnclosureGroup(self.fusion_client)
        encgrps = enc_grps.get()

        for encgrp in encgrps['members']:
            if encgrp['name'] == enc_grp_name:
                body['enclosureGroupUri'] = encgrp['uri']
                break
        if 'enclosureGroupUri' not in body:
            logger._log('Enclosure group %s does not exist' % enc_grp_name, level='WARN')

        ver = {3: self._make_body_4,
               4: self._make_body_4,
               101: self._make_body_101}

        # run the corresponding function
        if api in ver:
            return ver[api](body)
        else:
            # TODO: might want special handling other than Exception
            msg = "API version %d is not supported" % (api)
            raise Exception(msg)
    def make_body(self, api, body, lig_map):

        lig_grps = LogicalInterconnectGroup(self.fusion_client)
        ligs = lig_grps.get()
        body['ligs'] = {}

        if not api:
            api = self.fusion_client._currentVersion()

        for i in lig_map.keys():
            found_lig = 0
            for lig in ligs['members']:
                found_lig += 1
                if lig['name'] == lig_map[i]:
                    # Replace logicalInterconnectGroup name with uri.
                    body['ligs'][i] = lig['uri']
                    break
            if not found_lig:
                logger._log('Lig %s does not exist' % (lig_map[i]), level='WARN')

        ver = {3: self._make_body_4,
               4: self._make_body_4,
               101: self._make_body_101,
               199: self._make_body_101,
               200: self._make_body_200,
               299: self._make_body_300,
               300: self._make_body_300,
               500: self._make_body_500}

        # run the corresponding function
        if api in ver:
            return ver[api](body)
        else:
            # TODO: might want special handling other than Exception
            msg = "API version %d is not supported" % (api)
            raise Exception(msg)
示例#12
0
def get_vlan_details_from_manganese(hostname, username, password):
    """
    Gets vlan details from manganese ICM
    """
    port = 22
    ssh = paramiko.SSHClient()
    ssh.load_system_host_keys()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(hostname=hostname,
                port=port,
                username=username,
                password=password,
                look_for_keys=False,
                allow_agent=False)
    channel = ssh.invoke_shell(term='vt100',
                               width=200,
                               height=1000000,
                               width_pixels=0,
                               height_pixels=0)

    # Wait for Recv Ready after logging in.
    results = ''
    while channel.recv_ready() is False:
        time.sleep(10)
        logger._log('\nChannel receive ready status: \n %s' %
                    (channel.recv_ready()),
                    level='DEBUG')
    results += channel.recv(50000)
    logger._log("\nResults After Login: \n", level='DEBUG')

    # Send Show VLAN Command
    results = ''
    logger._log("\nSending 'show vlan' command.\n", level='DEBUG')
    channel.send('show vlan\n')
    while channel.recv_ready() is False:
        time.sleep(10)
        logger._log('\nChannel receive ready status: \n %s' %
                    (channel.recv_ready()),
                    level='DEBUG')
    results += channel.recv(500000)
    logger._log("Results after 'show vlan' command: \n %s" % (results),
                level='DEBUG')
    # Close SSH shell
    ssh.close()
    # Strip the header and footer from the output table and get only table rows
    results = "\n".join(results.split("\n")[:-2])
    table = ''.join(
        re.split(
            r'\r\nVLAN.*Ports\r\n----------------------------------------------------------------------',
            results)[1:])
    table = table.strip()
    table = table.split('\r\n')
    x = ""
    for line in table:
        line = ",".join(re.split(r'\s{2,}', line))
        x = x + "\n" + line
    # Convert row/line into Dictionary
    fnames = ["VLAN", "Ports"]
    results = csv.DictReader(x.splitlines(), fieldnames=fnames)
    dict_list = []
    for line in results:
        dict_list.append(line)
    return dict_list
def get_multi_rspan_details_from_ICM(hostname, username, password):
    port = 22
    ssh = paramiko.SSHClient()
    ssh.load_system_host_keys()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(hostname=hostname, username=username, password=password)
    channel = ssh.invoke_shell(term='vt100', width=200, height=1000000, width_pixels=0, height_pixels=0)

    results = ''
    # Wait for shell to receive command
    while channel.recv_ready() is False:
        time.sleep(2)
        logger._log('\nChannel receive ready status: \n %s' % (channel.recv_ready()), level='DEBUG')
    results += channel.recv(50000)
    logger._log("\nResults After Login: \n", level='DEBUG')

    results = ''
    logger._log("\nSending 'no pagination' command.\n", level='DEBUG')
    channel.send('no pagination\n')
    while channel.recv_ready() is False:
        time.sleep(2)
        logger._log('\nChannel receive ready status: \n %s' % (channel.recv_ready()), level='DEBUG')
    results += channel.recv(50000)
    logger._log("\nResults after 'no pagination' command: \n", level='DEBUG')

    logger._log("Sending 'sh monitor all' command.\n", level='DEBUG')
    channel.send('sh monitor all\n')
    results = ''
    while channel.recv_ready() is False:
        time.sleep(2)
        logger._log('\nChannel receive ready status: \n %s' % (channel.recv_ready()), level='DEBUG')
    results += channel.recv(50000)
    logger._log("Results after 'sh monitor all' command: \n %s" % (results), level='DEBUG')

    # Close SSH shell
    ssh.close()
    # Get the table rows only from 'sh monitor all' command output
    results = "\n".join(results.split("\n")[:-1])
    # Convert multiple Sessions info into list of tables
    tables = re.split(r' Session     : \d{1}\r\n -------\r\n Source Ports', results)[1:]
    # Process List of tables and get required RSPAN Session Info
    session_list = []
    for session in tables:
        print "Table before Splitting\n", session
        session = session.strip()
        session = session.split('\r\n')
        print "Table After Splitting\n", session
        dict = {k.strip(): v.strip() for k, v in (x.split(' : ') for x in session)}
        nw_vlan_id = dict['Rspan Vlan Id']
        destination_ports_list = []
        if dict['Destination Ports'] != 'None':
            destination_ports = dict['Destination Ports'].split(',')
            for dp in destination_ports:
                dp = 'Q' + dp.split('/')[-1]
                destination_ports_list.append(dp)
        source_ports_dict = {}
        Rx_ports_list = []
        if dict['Rx'] != 'None':
            Rx_ports = dict['Rx'].split(',')
            for rp in Rx_ports:
                rp = 'd' + rp.split('/')[-1]
                Rx_ports_list.append(rp)
        Tx_ports_list = []
        if dict['Tx'] != 'None':
            Tx_ports = dict['Tx'].split(',')
            for tp in Tx_ports:
                tp = 'd' + tp.split('/')[-1]
                Tx_ports_list.append(tp)
        Monitored_both_port_list = []
        if dict['Both'] != 'None':
            Monitored_both_ports = dict['Both'].split(',')
            for mbp in Monitored_both_ports:
                mbp = 'd' + mbp.split('/')[-1]
                Monitored_both_port_list.append(mbp)
        monitored_ports = {'Tx_ports': Tx_ports_list.sort(), 'Rx_ports': Rx_ports_list.sort(), 'Monitored_both_ports': Monitored_both_port_list.sort()}
        session_dict = {'nw_vlan_id': nw_vlan_id, 'destination_ports': destination_ports_list, 'monitored_ports': monitored_ports}
        session_list.append(session_dict)
    return session_list
def get_rspan_details_from_ICM(hostname, username, password):
    port = 22
    ssh = paramiko.SSHClient()
    ssh.load_system_host_keys()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(hostname=hostname, username=username, password=password)
    channel = ssh.invoke_shell(term='vt100', width=200, height=1000000, width_pixels=0, height_pixels=0)

    results = ''
    # Wait for shell to receive command
    while channel.recv_ready() is False:
        time.sleep(2)
        logger._log('\nChannel receive ready status: \n %s' % (channel.recv_ready()), level='DEBUG')
    results += channel.recv(50000)
    logger._log("\nResults After Login: \n", level='DEBUG')

    results = ''
    logger._log("\nSending 'no pagination' command.\n", level='DEBUG')
    channel.send('no pagination\n')
    while channel.recv_ready() is False:
        time.sleep(2)
        logger._log('\nChannel receive ready status: \n %s' % (channel.recv_ready()), level='DEBUG')
    results += channel.recv(50000)
    logger._log("\nResults after 'no pagination' command: \n", level='DEBUG')

    logger._log("Sending 'sh monitor all' command.\n", level='DEBUG')
    channel.send('sh monitor all\n')
    results = ''
    while channel.recv_ready() is False:
        time.sleep(2)
        logger._log('\nChannel receive ready status: \n %s' % (channel.recv_ready()), level='DEBUG')
    results += channel.recv(50000)
    logger._log("Results after 'sh monitor all' command: \n %s" % (results), level='DEBUG')

    # Close SSH shell
    ssh.close()

    # Get the table rows only from 'sh monitor all' command output
    table = "\n".join(results.split("\n")[5:-1])
    table = table.strip()
    table = table.split('\n')

    # Convert lines in table to dictionary
    dict = {k.strip(): v.strip() for k, v in (x.split(' : ') for x in table)}

    # Get required RSPAN session details from the dictionary
    nw_vlan_id = dict['Rspan Vlan Id']
    destination_port = 'Q' + dict['Destination Ports'].split('/')[-1]
    monitored_port = 'd' + dict['Both'].split('/')[-1]
    # Pack RSPAN session details into new dictionary and return the same
    dict2 = {'nw_vlan_id': nw_vlan_id, 'destination_port': destination_port, 'monitored_port': monitored_port}
    return dict2
示例#15
0
from selenium import webdriver
from selenium.common.exceptions import StaleElementReferenceException
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.remote.webelement import WebElement
import requests

from RoboGalaxyLibrary.common.decorators import deprecated
from RoboGalaxyLibrary.common.exceptions import FatalError
from RoboGalaxyLibrary.data import test_data
from RoboGalaxyLibrary.utilitylib import logging as logger

try:
    from robot.libraries.Screenshot import Screenshot
except RuntimeError as e:
    logger._log("Unable to import Screenshot. Cant open Display\n" + str(e),
                level='WARN')

# restrict logging messages from the requests modules to warning only
requests_log = logging.getLogger("requests")
requests_log.setLevel(logging.WARNING)

WAIT_SLEEP_TIME = 0.1
ROOT_XPATH = 'xpath=/html'

##############################################################################
# Generic functions
##############################################################################


def get_s2l():
    """ get_s2l
示例#16
0
 def Apic_FabricNode_get(self, APPLIANCE_IP, token, IPList):
     # This function will get the fabric nodes and validate the nodes Ip returned is equal to the IPList passed in this function
     import json
     import requests
     error = 0
     requestObj = HttpVerbs()
     GETurl = 'https://%s/api/node/class/fabricLooseNode.json' % (
         APPLIANCE_IP)
     cookies = {}
     cookies['APIC-Cookie'] = token
     logger._log("url is %s" % GETurl)
     Getresponse = requests.get(GETurl, cookies=cookies, verify=False)
     response = Getresponse.json()
     logger._log("json response is %s" % response)
     nodecount = response['totalCount']
     logger._log("node count is %s" % int(nodecount))
     nodeiplists = []
     i = 0
     j = int(nodecount) - 1
     while i <= j:
         if 'imdata' in response:
             imdata = response['imdata']
             fabricnode = imdata[i]
             fabricLooseNode = fabricnode['fabricLooseNode']
             attributes = fabricLooseNode['attributes']
             id = str(attributes['id'])
             if (id != '78:48:59:61:39:63' and id != '169.254.57.19'
                     and id != '10.10.5.185' and id != '10.10.0.208'
                     and id != '15.212.137.13' and id != '15.212.137.14'
                     and id != '15.212.137.17' and id != '15.212.137.18'
                     and id != '15.212.137.18' and id != '15.212.137.19'
                     and id != '15.212.137.20' and id != '15.212.137.21'
                     and id != '15.212.137.22'):
                 nodeiplists.append(id)
             i = i + 1
             continue
     logger._log('Node ip list from json Response is %s' % nodeiplists)
     nodeiplists1 = ",".join(nodeiplists)
     logger._log('Node ip list from data file is  %s' % IPList)
     if nodeiplists1 in IPList:
         logger._log("NodeIp list  matches %s" % nodeiplists1)
     else:
         logger._log("NodeIp list did not match %s" % nodeiplists1)
         error = error + 1
     if error != 0:
         logger._log("Node Ip did not match ")
         return False
示例#17
0
 def validate_Apic_topology(self, APPLIANCE_IP, token, APIC_TOPOLOGY,
                            NodeIp):
     # This function will get the fabric nodes and validate the nodes Ip returned is equal to the IPList passed in this function
     import json
     import requests
     error = 0
     requestObj = HttpVerbs()
     GETurl = 'https://%s/api/node/mo/topology/lsnode-%s.json?query-target=children&target-subtree-class=fabricLooseAttLink' % (
         APPLIANCE_IP, NodeIp)
     cookies = {}
     cookies['APIC-Cookie'] = token
     logger._log("url is %s" % GETurl)
     Getresponse = requests.get(GETurl, cookies=cookies, verify=False)
     response = Getresponse.json()
     logger._log("json response is %s" % response)
     nodecount = response['totalCount']
     logger._log("node count is %s" % int(nodecount))
     i = 0
     j = int(nodecount) - 1
     if int(nodecount) > 0:
         while i <= j:
             if 'imdata' in response:
                 imdata = response['imdata']
                 fabricnode = imdata[i]
                 fabricLooseNode = fabricnode['fabricLooseAttLink']
                 attributes = fabricLooseNode['attributes']
                 hostDn = str(attributes['hostDn'])
                 logger._log("Host DN from response is %s" % hostDn)
                 logger._log("Expected toplogy is %s" % APIC_TOPOLOGY)
                 if hostDn:
                     if str(hostDn) == str(APIC_TOPOLOGY):
                         logger._log("Topology graph established %s" %
                                     hostDn)
                     else:
                         return False
                 else:
                     return False
                 i = i + 1
                 continue
         return True
     else:
         return False
    def send_response(self, cmdstr):
        # execute command
        logger._log("{!s}\n  Command: {!s} \n{!s}\n".format(("=" * 40), cmdstr,
                                                            ("=" * 40)))

        self.session.send(cmdstr)
 def login_exit(self, timeout=15):
     logger._log("\n{!s} END {!s}\n".format(("=" * 20), ("=" * 20)))
     self.client.close()