예제 #1
0
    def __init__(self, **kwargs):
        """
        :param host:
            **REQUIRED** hostname or IP address of device to telnet to
        :param user:
            *OPTIONAL* Login user name. If not provided will be derived from
            Toby framework defaults.
        :param password:
            *OPTIONAL* Login Password. If not provided will be derived from
            Toby framework defaults.
        :param connect_mode:
            *OPTIONAL* Connection mode to device. Default is telnet. Supported
            value is telnet.
        """
        if 'host' not in kwargs:
            raise TobyException("Mandatory Parameter host missing")
        # if username and password are not specified by caller
        kwargs['os'] = kwargs.get('osname', 'WINDOWS')
        if not kwargs.get('user', None):
            kwargs['user'], kwargs['password'] = credentials.get_credentials(
                os=kwargs.get('osname', 'WINDOWS'))
        host = kwargs.get('host')
        connect_mode = kwargs.get('connect_mode', 'telnet')
        super(Windows, self).__init__(**kwargs)
        self.log(message='Trying to connect to device ' + host + ' via ' +
                 connect_mode + ' ...')
        self.prompt = 'Toby-%s-%s' % (os.getpid(), host)
        self.prompt += '%'
        self.port = kwargs.get('text_port')
        try:
            if connect_mode == 'ssh':
                self.prompt = '>\s?'
                handle = SshConn(host=host,
                                 user=kwargs['user'],
                                 password=kwargs['password'],
                                 initialize_command='cd')
            else:
                handle = TelnetConn(host=host,
                                    user=kwargs['user'],
                                    password=kwargs['password'],
                                    port=self.port)
            self.handle = handle
            self.log(message='Connection to ' + host + ' via ' + connect_mode +
                     ' is successful.')
        except:
            raise TobyException(
                "Cannot connect text channel via %s to %s Device %s" %
                (connect_mode, kwargs['os'], host),
                host_obj=self)

        if self.port == 23:
            self.set_shell_prompt(prompt=self.prompt)
        else:
            self.prompt = '>\s?'
        self.connected = 1
        self.response = ''
        self.mode = 'shell'
예제 #2
0
    def __init__(self, system_data=None):
        """
        IxVeriwave abstraction layer

        :param  system_data  *MANDATORY* Dictionary of IxVeriwave information
          Example:
          system_data =
              system:
                primary:
                  controllers:
                    re0:
                      domain: englab.juniper.net
                      hostname: branch-ixveriwave
                      isoaddr: 47.0005.80ff.f800.0000.0108.0001.0102.5523.0232.00
                      loop-ip: 10.255.230.232
                      loop-ipv6: abcd::10:255:230:232
                      mgt-intf-name: mgt.0
                      mgt-ip: 10.204.230.232
                      mgt-ipv6: abcd::10:204:230:232
                      osname: JunOS
                  make: ixia
                  model: ixveriwave ata100
                  name: branch-ixveriwave
                  osname: JunOS


        :return: IxVeriwave object
        """
        self.expect_timeout = 20  # Timeout for telnet expect
        self.telnet_handle = None  # Telnet object on which commands will be invoked
        self.prompt = r"ready>\s?"  # This is the main prompt in the IxVeriwave console
        if system_data:
            self.host_args = dict(
            )  # Used to hold host arguments like user, password, osname, etc.
            sys_pri = system_data['system']['primary']
            if 'name' in sys_pri:
                self.host_args['host'] = sys_pri['name']
            controller_key = list(sys_pri['controllers'].keys())[0]
            self.chassis = sys_pri['controllers'][controller_key]['mgt-ip']

            if 'osname' in sys_pri['controllers'][controller_key]:
                self.host_args['os'] = sys_pri['controllers'][controller_key][
                    'osname']
            else:
                self.host_args['os'] = 'IxVeriwave'
            # Getting user/password for login
            self.host_args['user'], self.host_args[
                'password'] = credentials.get_credentials(
                    os=self.host_args['os'])
            # Checking to see if a username has been passed via fv knob
            if 'user' in sys_pri['controllers'][controller_key]:
                self.host_args['user'] = sys_pri['controllers'][
                    controller_key]['user']
            self.prompt = "{} {}".format(self.host_args['user'],
                                         self.prompt).encode(encoding='ascii')
            super(IxVeriwave, self).__init__(**self.host_args)
예제 #3
0
def get_logs_and_stats_after_test(all_controller_handles_dict):
    """
        pulling logs and stats at the end of each
        test case
    """
    t.log("entering get logs and stats after test")
    logdir = get_log_dir()
    test_case = BuiltIn().get_variable_value('${TEST NAME}')
    logdir = logdir + '/' + test_case
    if not os.path.exists(logdir):
        os.makedirs(logdir)
    for key in all_controller_handles_dict:
        t.log(all_controller_handles_dict)
        controller_handle = all_controller_handles_dict[key]
        username, passwrd = get_credentials(os='JUNOS')
        scp_obj = SCP(host=controller_handle.host,
                      user=username,
                      password=passwrd)
        scp_obj.get_file('/var/log/messages',
                         logdir + '/' + '%s_messages.messages' % (key))
        if controller_handle.is_master():
            op = controller_handle.shell(
                command="ps | grep rtsockmon").response()
            flag = 0
            for line in op.splitlines():
                line = line.strip()
                if 'rtsockmon -rt' in line:
                    pid = line.split(' ')[0]
                if pid:
                    controller_handle.shell(command="kill -9 " +
                                            pid).response()
                    flag = 1
            if flag == 0:
                controller_handle.log("\nprocess is not running")
            scp_obj = SCP(host=controller_handle.host,
                          user=username,
                          password=passwrd)
            scp_obj.get_file('/var/log/%s_rtsockmon.txt' % (key),
                             logdir + '/' + '%s_rtsockmon.log' % (key))
        controller_handle.cli(
            command=
            "request support information | save /var/log/%s_req_sup_info.log" %
            (key)).response()
        scp_obj = SCP(host=controller_handle.host,
                      user=username,
                      password=passwrd)
        scp_obj.get_file('/var/log/%s_req_sup_info.log' % (key),
                         logdir + '/' + '%s_req_sup_info.log' % (key))
    t.log("exiting get logs and stats after test")
예제 #4
0
파일: warp17.py 프로젝트: SrijaGupta/file
    def __init__(self, chassis=None, system_data=None):
        """
        Warp17 abstraction layer for HLTAPI

        -- Workflow 1 --
        :param  system_data:  *MANDATORY* Dictionary of Warp17 information
          rt0:
            interfaces:
              intf1:
                name: 1/8
              intf2:
                name: 1/9
            system:
              primary:
                appserver: wf-appserver2.englab.juniper.net
                controllers:
                  unknown:
                    domain: englab.juniper.net
                    hostname: wf-warp17chassis2
                    mgt-intf-name: mgt0
                    mgt-ip: 10.9.1.107
                    osname: IxOS
                make: warp17
                model: xgs12
                name: wf-ixchassis2
                osname: IxOS

        -- Workflow 2 --
        :param  host  *MANDATORY* FQDN/mgt-ip of of chassis


        :return: Warp17 object
        """
        self.chassis = None
        self.interfaces = None
        self.model = 'Unknown'
        self.intf_to_port_map = dict()
        self.port_to_handle_map = dict()
        self.session_info = None
        self.handle_to_port_map = None
        self.login_complete = False
        self.log_dir = get_log_dir()
        self.clientport = None
        self.serverport = None
        atexit.register(self.cleanup)
        self.username, self.password = credentials.get_credentials(os='Unix')

        self.connect_kwargs = {
            'virtual_machine': 0,
            'ring_if_pairs': None,
            'dpdk_dev_bind_path': None,
            'host_name': "localhost",
            'ucb_pool_sz': 0,
            'tcb_pool_sz': 0,
            'lcores': None
        }

        if system_data:

            controller_key = list(
                system_data['system']['primary']['controllers'].keys())[0]

            if 'user' in system_data['system']['primary']['controllers'][controller_key] and \
                system_data['system']['primary']['controllers'][controller_key]['user']:
                self.username = system_data['system']['primary'][
                    'controllers'][controller_key]['user']
            if 'password' in system_data['system']['primary']['controllers'][controller_key] and \
                system_data['system']['primary']['controllers'][controller_key]['password']:
                self.password = system_data['system']['primary'][
                    'controllers'][controller_key]['password']

            kwargs = dict()
            kwargs['host'] = self.chassis = system_data['system']['primary'][
                'name']
            kwargs['hostname'] = self.chassis = system_data['system'][
                'primary']['name']
            kwargs['os'] = system_data['system']['primary']['controllers'][
                controller_key]['osname']
            super(Warp17, self).__init__(**kwargs)

            if 'mgt-ip' in system_data['system']['primary']['controllers'][
                    controller_key]:
                self.chassis = system_data['system']['primary']['controllers'][
                    controller_key]['mgt-ip']
            self.model = system_data['system']['primary']['model'].upper()

            warp17_options_str = system_data['system']['primary']['warp17']
            if warp17_options_str == 'enable':
                t.log(level="INFO", message="Using default warp17 options")
            else:
                option_list = warp17_options_str.split(':')
                for option in option_list:
                    key, value = option.split('=')
                    if key and value and key in self.connect_kwargs:
                        self.connect_kwargs[key] = value

        elif chassis:
            self.chassis = chassis
        else:
            raise TobyException(
                "Missing either system_data (Workflow 1) or chassis (Workflow 2) parameter"
            )

        if not self.chassis:
            raise TobyException(
                "Unable to determine chassis host information! Check for valid in init yaml file.",
                host_obj=self)

        self.connect_info = None
        self.log("CHASSIS= " + str(self.chassis))

        self.warp17 = Warp17api(server_name=self.chassis)  # pylint: disable=import-error
예제 #5
0
    def __init__(self, chassis=None, landslide_manager=None, system_data=None, landslide_lib_path=None, landslide_jre_path=None, landslide_tcl_bin=None):
        """
        Landslide abstraction layer for HLTAPI

        -- Workflow 1 --
        :param  system_data:  *MANDATORY* Dictionary of Spirent information
        system:
        primary:
          controllers:
            if0:
              domain: englab.juniper.net
              hostname: Systest-Landslide
              isoaddr: 47.0005.80ff.f800.0000.0108.0001.0102.5500.7000.00
              loop-ip: 10.255.7.0
              loop-ipv6: abcd::10:255:7:0
              mgt-intf-name: eth0
              mgt-ip: 10.9.4.6
              mgt-ipv6: abcd::10:9:4:6
              osname: SPIRENT
          cube:
            - COMMON-LISP::OR
            - wf-626-systest
          make: spirent
          model: spt-c100-ts
          name: Systest-Landslide
          osname: spirent
          landslide_manager: 10.4.4.42

        -- Workflow 2 --
        :param  host  *MANDATORY* FQDN/mgt-ip of of chassis
        :param  landslide_manager  *MANDATORY* landslide_manager - manager of test servers

        :return: Landslide object
        """

        self.debug = False
        self.chassis = None
        self.session_info = None
        self.intf_to_port_map = None
        self.log_dir = get_log_dir()
        atexit.register(self.cleanup)
        self.ls = None
        self.user_functions = dict()

        if landslide_lib_path and landslide_jre_path and landslide_tcl_bin:
            self.lib_path = landslide_lib_path
            self.jre_path = landslide_jre_path
            self.tcl = landslide_tcl_bin
        else:
            environment = yaml.safe_load(open(os.path.join(os.path.dirname(credentials.__file__), "environment.yaml")))
            self.lib_path = environment['landslide-lib-path']
            self.jre_path = environment['landslide-jre-path']
            self.tcl = environment['landslide-tcl-bin']

        if system_data:

            controller_key = list(system_data['system']['primary']['controllers'].keys())[0]

            if 'user' in system_data['system']['primary']['controllers'][controller_key]:
                self.username = system_data['system']['primary']['controllers'][controller_key]['user']
            if 'password' in system_data['system']['primary']['controllers'][controller_key]:
                self.password = system_data['system']['primary']['controllers'][controller_key]['password']

            kwargs = dict()
            kwargs['host'] = self.chassis = system_data['system']['primary']['name']
            kwargs['hostname'] = self.chassis = system_data['system']['primary']['name']
            kwargs['os'] = system_data['system']['primary']['controllers'][controller_key]['osname']
            super(Landslide, self).__init__(**kwargs)

            if 'debug' in system_data['system']['primary']:
                self.debug = system_data['system']['primary']['debug']
            if 'mgt-ip' in system_data['system']['primary']['controllers'][controller_key]:
                self.chassis = system_data['system']['primary']['controllers'][controller_key]['mgt-ip']
            self.landslide_manager = system_data['system']['primary']['landslide-manager']
        elif chassis:
            self.chassis = chassis
            self.landslide_manager = landslide_manager

        else:
            raise TobyException("Missing either system_data (Workflow 1) or chassis (Workflow 2) parameter")

        if not self.chassis:
            raise TobyException("Unable to determine chassis host information! Check for valid labserver or mgt-ip in init yaml file.")

        self.connect_info = None
        self.log("CHASSIS= " + str(self.chassis))
        cred = credentials.get_credentials(os='Landslide')
        self.username = cred['USERNAME']
        self.password = cred['PASSWORD']
        self.telnetuser = cred['TELNETUSERNAME']
        self.telnetpwd = cred['TELNETPASSWORD']

        self.wait = 1
        self.telnet_handle = None
        self.version = self._get_version()
        sys.path.append(self.lib_path)
        self._set_envs()

        #resetting sys.argv[0] is only way to get spirent htlapi logs to go to the right place
        #executable = sys.argv[0]
        #sys.argv[0] = self.log_dir
        self.ls = __import__('ls')
        #sys.argv[0] = executable
        self.log("Landslide Chassis Initialization Complete")
예제 #6
0
    def __init__(self, system_data):
        """
        Breaking Point abstraction layer

        :param  system_data  *MANDATORY* Dictionary of Breaking Point information
          Example:
          system_data =
            system:
              primary:
                controllers:
                  unknown:
                    domain: englab.juniper.net
                    hostname: wf-bpchassis2
                    mgt-intf-name: mgt0
                    mgt-ip: 10.9.1.111
                    osname: BreakingPoint
                make: breaking point
                model: bps123
                name: wf-bpchassis2
                osname: breaking point


        :return: breakingpoint object
        """

        self.bps = None
        self.port_list = None
        self.breakingpoint_version = None
        self.intf_to_port_map = None
        self.debug = False
        self.wait = 1
        self.group = 1
        atexit.register(self.cleanup)

        self.username, self.password = credentials.get_credentials(
            os='Breakingpoint')

        environment = yaml.safe_load(
            open(
                os.path.join(os.path.dirname(credentials.__file__),
                             "environment.yaml")))
        self.lib_path = environment['breakingpoint-lib-path']

        controller_key = list(
            system_data['system']['primary']['controllers'].keys())[0]
        self.chassis = system_data['system']['primary']['controllers'][
            controller_key]['mgt-ip']

        if system_data['system']['primary']['controllers'][controller_key][
                'user']:
            self.username = system_data['system']['primary']['controllers'][
                controller_key]['user']
        if system_data['system']['primary']['controllers'][controller_key][
                'password']:
            self.password = system_data['system']['primary']['controllers'][
                controller_key]['password']
        if 'debug' in system_data['system']['primary']:
            self.debug = True
        if 'group' in system_data['system']['primary']:
            try:
                self.group = int(system_data['system']['primary']['group'])
                if self.group < 1 or self.group > 12:
                    raise TobyException("Illegal value for fv-breakingpoint-group (" + \
                                        str(system_data['system']['primary']['group']) + "). Should be an integer 1-12.")

            except Exception:
                raise TobyException(
                    "Illegal value for fv-breakingpoint-group (" +
                    str(system_data['system']['primary']['group']) +
                    "). Should be an integer 1-12.")

        kwargs = dict()
        kwargs['host'] = self.hostname = system_data['system']['primary'][
            'name']
        kwargs['hostname'] = self.hostname = system_data['system']['primary'][
            'name']
        kwargs['os'] = system_data['system']['primary']['controllers'][
            controller_key]['osname']
        kwargs['user'] = self.username
        kwargs['password'] = self.password
        super(Breakingpoint, self).__init__(**kwargs)

        if not self.username:
            raise TobyException("Username and password cannot be determined",
                                host_obj=self)

        self.log("CHASSIS= " + self.chassis)

        self.version = self._get_version()
        self.lib_version = self._get_lib_version()
        self._set_envs()
        from bpsRest import BPS  # pylint: disable=import-error

        self.bps = BPS(self.chassis, self.username, self.password)
예제 #7
0
    def __init__(self,
                 chassis=None,
                 system_data=None,
                 avalanche_tcl_bin=None,
                 avalanche_lib_path=None,
                 avalanche_threats=None,
                 avalanche_jre_path=None):
        """
        Avalanche abstraction layer for HLTAPI

        -- Workflow 1 --
        :param  system_data:  *MANDATORY* Dictionary of Avalanche information
          rt0:
            interfaces:
              intf1:
                name: 1/8
              intf2:
                name: 1/9
            system:
              primary:
                appserver: wf-appserver2.englab.juniper.net
                controllers:
                  unknown:
                    domain: englab.juniper.net
                    hostname: wf-avchassis2
                    mgt-intf-name: mgt0
                    mgt-ip: 10.9.1.107
                    osname: IxOS
                make: avalanche
                model: xgs12
                name: wf-ixchassis2
                osname: IxOS

        -- Workflow 2 --
        :param  host  *MANDATORY* FQDN/mgt-ip of of chassis


        :return: Avalanche object
        """
        self.chassis = None
        self.interfaces = None
        self.model = 'Unknown'
        self.platform_type = 'STC'
        self.intf_to_port_map = dict()
        self.port_to_handle_map = dict()
        self.session_info = None
        self.handle_to_port_map = None
        self.login_complete = False

        #self.tcl = '/volume/systest-proj/apptest/local/ActiveTcl-8.4/bin/tclsh'
        #self.tcl = '/volume/systest-proj/apptest/local/bin/tclsh8.6'
        self.log_dir = get_log_dir()
        self.clientport = None
        self.serverport = None
        atexit.register(self.cleanup)
        self.username, self.password = credentials.get_credentials(
            os='Spirent')

        if avalanche_lib_path and avalanche_tcl_bin and avalanche_jre_path and avalanche_threats:
            self.lib_path = avalanche_lib_path
            self.tcl_bin = avalanche_tcl_bin
            self.jre_path = avalanche_jre_path
            self.threat_path = avalanche_threats
        else:
            environment = yaml.safe_load(
                open(
                    os.path.join(os.path.dirname(credentials.__file__),
                                 "environment.yaml")))
            self.lib_path = environment['avalanche-lib-path']
            self.tcl_bin = environment['avalanche-tcl-bin']
            self.jre_path = environment['avalanche-jre-path']
            self.threat_path = environment['avalanche-threats']

        self.api_path = self.lib_path + '/Avalanche/PythonAPI/1.0.0'

        if system_data:

            controller_key = list(
                system_data['system']['primary']['controllers'].keys())[0]

            if system_data['system']['primary']['controllers'][controller_key][
                    'user']:
                self.username = system_data['system']['primary'][
                    'controllers'][controller_key]['user']
            if system_data['system']['primary']['controllers'][controller_key][
                    'password']:
                self.password = system_data['system']['primary'][
                    'controllers'][controller_key]['password']

            kwargs = dict()
            kwargs['host'] = self.chassis = system_data['system']['primary'][
                'name']
            kwargs['hostname'] = self.chassis = system_data['system'][
                'primary']['name']
            kwargs['os'] = system_data['system']['primary']['controllers'][
                controller_key]['osname']
            kwargs['user'] = self.username
            kwargs['password'] = self.password
            super(Avalanche, self).__init__(**kwargs)

            if 'api-path' in system_data['system']['primary']:
                self.log("Overriding existing av.py path with: " +
                         system_data['system']['primary']['api-path'])
                self.api_path = system_data['system']['primary']['api-path']
            if 'mgt-ip' in system_data['system']['primary']['controllers'][
                    controller_key]:
                self.chassis = system_data['system']['primary']['controllers'][
                    controller_key]['mgt-ip']
            self.model = system_data['system']['primary']['model'].upper()
            match = re.search(r'(^C100$|3100|^C100U$)', self.model, re.I)

            if match and not (system_data['system']['primary']['controllers'][controller_key]['user'] \
                and system_data['system']['primary']['controllers'][controller_key]['password']):
                if match.group(1) == 'C100' or match.group(1) == 'C100U':
                    self.log("Model %s, so Overriding username and password" %
                             match.group(1))
                    self.username = '******'
                    self.password = '******'
                    self.log("Login:"******", Password:"******"Model 3100, so Overriding username and password")
                    self.username = '******'
                    self.password = ''
                    self.log("Login:"******", Password:"******"ERROR: Must include fv-avalanche-license-path for models starting with C100",
                        host_obj=self)
                self.platform_type = self.model

        elif chassis:
            self.chassis = chassis
        else:
            raise TobyException(
                "Missing either system_data (Workflow 1) or chassis (Workflow 2) parameter"
            )

        if not self.chassis:
            raise TobyException(
                "Unable to determine chassis host information! Check for valid in init yaml file.",
                host_obj=self)

        self.connect_info = None
        self.log("CHASSIS= " + str(self.chassis))

        self.wait = 1
        self.telnet_handle = None
        self.version = self._get_version()
        self._set_envs()
        sys.path.append(self.api_path)
        self.log("API PATH= " + self.api_path)
        executable = sys.argv[0]
        sys.argv[0] = self.log_dir
        try:
            self.av = __import__('av')  # pylint: disable=invalid-name
        except Exception as err:
            raise TobyException("Unable to import 'av' at path " +
                                self.api_path + ": " + str(err),
                                host_obj=self)
        sys.argv[0] = executable

        self.av.new(CHASSIS=self.chassis, TYPE=self.platform_type)
예제 #8
0
파일: ixia.py 프로젝트: SrijaGupta/file
    def __init__(self, system_data=None, chassis=None, appserver=None, license_server=None, ixia_lib_path=None):
        """
        IXIA abstraction layer for HLTAPI

        -- Workflow 1 --
        :param  system_data  *MANDATORY* Dictionary of IXIA information
          Example:
          system_data =
            system:
              primary:
                appserver: wf-appserver2.englab.juniper.net
                controllers:
                  unknown:
                    domain: englab.juniper.net
                    hostname: wf-ixchassis2
                    mgt-intf-name: mgt0
                    mgt-ip: 10.9.1.107
                    osname: IxOS
                license_server: sv8-pod1-ixlic1.englab.juniper.net
                make: ixia
                model: xgs12
                name: wf-ixchassis2
                osname: IxOS

        -- Workflow 2 --
        :param  chassis  *MANDATORY* Name of chassis
        :param  appserver  *MANDATORY* Name of tcl server
        :param  license_server  *MANDATORY* Name of chassis

        :return: ixia object
        """
        self.virtual = False
        self.port_list = None
        self.session_info = None
        self.handle_to_port_map = None
        self.port_to_handle_map = None
        self.intf_to_port_map = None
        self.major_minor_version = None
        self.physical_port_type = 'fiber'
        self.user_functions = dict()
        self.connect_args = dict()
        self.cleanup_session_args = None
        self.port_order = None
        self.interfaces = None
        self.port = 8009
        self.connect_to_current_session = False
        self.connect_to_current_session_args = dict() # args just for connecting to current session
        atexit.register(self.cleanup)
        self.min_version = None
        self.username, self.password = credentials.get_credentials(os='Ixia')
        self.port_type = dict()
        # Ixia API handles
        self._ixiangpf = None
        self._ixiaixnet = None

        if ixia_lib_path:
            self.lib_path = ixia_lib_path
        else:
            environment = yaml.safe_load(open(os.path.join(os.path.dirname(credentials.__file__), "environment.yaml")))
            self.lib_path = environment['ixia-lib-path']
        if system_data:
            sys_pri = system_data['system']['primary']
            controller_key = list(sys_pri['controllers'].keys())[0]
            self.chassis = sys_pri['controllers'][controller_key]['mgt-ip']

            # Instantiate host object for logging
            host_args = dict()
            if 'name' in sys_pri:
                host_args['host'] = sys_pri['name']
            else:
                raise TobyIxiaException("Missing 'name' from 'primary' system stanza")
            if 'osname' in sys_pri['controllers'][controller_key]:
                host_args['os'] = sys_pri['controllers'][controller_key]['osname']
            else:
                raise TobyIxiaException("Missing 'osname' from controller " + controller_key + " stanza")
            super(Ixia, self).__init__(**host_args)


            # connect user fv- knob information and materialize kwargs for Ixia connect() call
            if 'appserver' in sys_pri:
                self.connect_args['ixnetwork_tcl_server'] = sys_pri['appserver']
            if 'appserver-port' in sys_pri:
                self.connect_args['ixnetwork_tcl_server'] = sys_pri['appserver'] + ':' + str(sys_pri['appserver-port'])
                self.port = sys_pri['appserver-port']
            if 'appserver-username' in sys_pri:
                self.connect_args['user_name'] = sys_pri['appserver-username']
            if 'appserver-password' in sys_pri:
                self.connect_args['user_password'] = sys_pri['appserver-password']
            if 'return-detailed-handles' in sys_pri:
                if sys_pri['return-detailed-handles'] == 'disable':
                    self.connect_args['return_detailed_handles'] = 0
            if 'config-file' in sys_pri:
                self.connect_args['config_file'] = sys_pri['config-file']
            else:
                self.connect_args['reset'] = 1
            if sys_pri['model'].lower().startswith('ixvm') or sys_pri['model'].lower().startswith('vixia'):
                self.virtual = True
                self.model = sys_pri['model'].lower()
                self.log(level='INFO', message="IXIA Type= Virtual")
                if 'license_server' in sys_pri:
                    self.connect_args['ixnetwork_license_servers'] = sys_pri['license_server']
                if 'license_type' in sys_pri:
                    if sys_pri['license_type'].startswith('tier'):
                        self.connect_args['ixnetwork_license_type'] = 'mixed_' + sys_pri['license_type']
                    else:
                        self.connect_args['ixnetwork_license_type'] = sys_pri['license_type']
            else:
                self.log(level='INFO', message="IXIA Type= Physical")

            if 'connect-args' in sys_pri and type(sys_pri['connect-args']) is dict:
                self.connect_args.update(sys_pri['connect-args'])
            if 'cleanup-session-args' in sys_pri and type(sys_pri['cleanup-session-args']) is dict:
                self.cleanup_session_args = sys_pri['cleanup-session-args']
            if 'port-order' in sys_pri:
                self.port_order = sys_pri['port-order']
            if 'connect-to-current-session' in sys_pri and sys_pri['connect-to-current-session'] == 'enable':
                self.connect_to_current_session = True
                self.connect_to_current_session_args['ixnetwork_tcl_server'] = self.connect_args['ixnetwork_tcl_server']
                # adding only connect-args for current session (no other arguments so can preserve session)
                if 'connect-args' in sys_pri and type(sys_pri['connect-args']) is dict:
                    self.connect_to_current_session_args.update(sys_pri['connect-args'])

            if 'min-version' in sys_pri and type(sys_pri['min-version']) is str:
                self.min_version = sys_pri['min-version']
                self.log(level='info', message="Ixia Minimum Chassis Version is set to: "+ sys_pri['min-version'])

            # Ensure mandatory connect() args are satisfied
            if 'ixnetwork_tcl_server' not in self.connect_args:
                raise TobyIxiaException("Missing appserver information (ixnetwork_tcl_server).  This may be provided via 'fv-ixia-appserver'"
                                    "knob, or via 'fv-ixia-connect-args'.", host_obj=self)
            if sys_pri['model'].lower().startswith('ixvm') or sys_pri['model'].lower().startswith('vixia'):
                if 'ixnetwork_license_servers' not in self.connect_args:
                    raise TobyIxiaException("Missing VM licensing information (ixnetwork_license_servers)." + \
                                        "This may be provided via 'fv-ixia-license-server' knob, or via 'fv-ixia-connect-args'.",
                                        host_obj=self)
                if 'ixnetwork_license_type' not in self.connect_args:
                    self.connect_args['ixnetwork_license_type'] = 'mixed_tier1'


        elif chassis and appserver:
            self.chassis = chassis
            self.appserver = appserver
            if license_server:
                self.license_server = license_server
        else:
            raise TobyIxiaException("Missing either system_data (Workflow 1) or chassis/appserver"
                                "/license_server (Workflow 2) parameters", host_obj=self)

        self.intf_status = None
        self.log(level='info', message="CHASSIS= " + self.chassis)
        self.log(level='info', message="APPSERVER= " + self.connect_args['ixnetwork_tcl_server'])

        self.wait = 1
        self.telnet_handle = None
        self.version = self._get_version()
        if self.min_version:
            if(float(self.version) < float(self.min_version)):
                raise TobyIxiaChassisConnectException("Ixia Minimum Chassis Version Check Failed", host_obj=self)
        if self.virtual:
            result = self._configure_promiscuous()
            if not result:
                self.log(level='WARN', message="Unable to set Promiscuous mode on IXIA virtual chassis")
            else:
                self.log(level='info', message="Successfully set Promiscuous mode on IXIA virtual chassis")
            if self.chassis_type is not None:
               if self.model.startswith('vixia') and re.search('Virtual Load Module', self.chassis_type, re.I):  
                   self.log(level='WARN', message="Virtual ixia chassis type is not correct as virtual modeli defined in params")
        self.ixia_lib_version = self._get_lib_version()
        self._set_envs()
        # Import core modules for native IXIA APIs
        # disable import-error because dynamic ENV changes based on IXIA version make it possible to import ok
        from ixiatcl import IxiaTcl # pylint: disable=import-error
        from ixiahlt import IxiaHlt # pylint: disable=import-error
        from ixiangpf import IxiaNgpf # pylint: disable=import-error
#        from ixiaerror import IxiaError # pylint: disable=import-error

        self.ixiatcl = IxiaTcl()
        self.ixiahlt = IxiaHlt(self.ixiatcl)
        self._ixiangpf = IxiaNgpf(self.ixiahlt)

        # Import extended ixia modules with functions
        # from jnpr/toby/trafficgen/ixia
        current_dir = os.path.dirname(os.path.abspath(
            inspect.getfile(inspect.currentframe())))
        user_module_dir = re.sub(r"jnpr\/toby.*", "jnpr/toby/trafficgen/ixia", current_dir)
        sys.path.append(user_module_dir)
        file_list = list(filter(lambda x: os.path.isfile(os.path.join(user_module_dir, x)), os.listdir(user_module_dir)))
        for file_name in file_list:
            if file_name.endswith('.py') and not file_name.startswith('__'):
                module = re.sub(r"\.py$", "", file_name)
                obj = __import__(module)
                function_list = [o for o in inspect.getmembers(obj)
                                 if inspect.isfunction(o[1])]
                for function_tuple in function_list:
                    function_name, function = function_tuple
                    if function_name in self.user_functions:
                        raise TobyIxiaException("Duplicate functions in user contributed modules", host_obj=self)
                    self.user_functions[function_name] = function
예제 #9
0
    def __init__(self, system_data=None, chassis=None, appserver=None):
        """
        IxLoad abstraction layer for HLTAPI

        -- Workflow 1 --
        :param  system_data  *MANDATORY* Dictionary of IxLoad information
          Example:
          system_data =
            system:
              primary:
                appserver: wf-appserver2.englab.juniper.net
                controllers:
                  unknown:
                    domain: englab.juniper.net
                    hostname: wf-ixchassis2
                    mgt-intf-name: mgt0
                    mgt-ip: 10.9.1.107
                    osname: IxOS
                make: ixia
                model: xgs12
                name: wf-ixchassis2
                osname: IxOS

        -- Workflow 2 --
        :param  chassis  *MANDATORY* Name of chassis
        :param  appserver  *MANDATORY* Name of tcl server

        :return: ixload object
        """
        self.port_list = None
        self.handle_to_port_map = None
        self.port_to_handle_map = None
        atexit.register(self.cleanup)
        self.intf_to_port_map = None
        self.interfaces = None
        self.session = None
        self.session_url = None
        self.user_functions = dict()
        self.username, self.password = credentials.get_credentials(os='Ixia')
        self.reconnect = None
        # IxLoad API handle
        self.ixload = None

        environment = yaml.safe_load(
            open(
                os.path.join(os.path.dirname(credentials.__file__),
                             "environment.yaml")))
        self.lib_path = environment['ixia-lib-path']

        if system_data:
            system = system_data['system']['primary']
            controller_key = list(system['controllers'].keys())[0]

            kwargs = dict()
            kwargs['host'] = self.hostname = system['name']
            kwargs['hostname'] = self.hostname = system['name']
            kwargs['os'] = system['controllers'][controller_key]['osname']
            super(IxLoad, self).__init__(**kwargs)

            # Set appserver
            if 'appserver' in system:
                self.appserver = system['appserver']
            else:
                raise TobyException(
                    "Missing appserver from 'primary' stanza: " +
                    str(system_data),
                    host_obj=self)
            # Specify chassis
            self.chassis = system['controllers'][controller_key]['mgt-ip']
            if 'ixlod-session' in system:
                self.reconnect = system['ixlod-session']

        elif chassis and appserver:
            self.chassis = chassis
            self.appserver = appserver
        else:
            raise TobyException(
                "Missing either system_data (Workflow 1) or chassis/appserver parameters",
                host_obj=self)

        self.intf_status = None
        self.log(level='info', message="CHASSIS= " + self.chassis)
        self.log(level='info', message="APPSERVER= " + self.appserver)

        self.wait = 1
        self.telnet_handle = None
        self.version = self._get_version()
        self._set_envs()
        current_dir = os.path.dirname(
            os.path.abspath(inspect.getfile(inspect.currentframe())))
        user_module_dir = re.sub(r"jnpr\/toby.*",
                                 "jnpr/toby/trafficgen/ixia/ixload",
                                 current_dir)
        sys.path.append(user_module_dir)
        file_list = list(
            filter(lambda x: os.path.isfile(os.path.join(user_module_dir, x)),
                   os.listdir(user_module_dir)))
        for file_name in file_list:
            if file_name.endswith('.py') and not file_name.startswith('__'):
                module = re.sub(r"\.py$", "", file_name)
                obj = __import__(module)
                function_list = [
                    o for o in inspect.getmembers(obj)
                    if inspect.isfunction(o[1])
                ]
                for function_tuple in function_list:
                    function_name, function = function_tuple
                    if function_name in self.user_functions:
                        raise TobyException(
                            "Duplicate functions in user contributed modules",
                            host_obj=self)
                    self.user_functions[function_name] = function
        self.connection = None
예제 #10
0
파일: spirent.py 프로젝트: SrijaGupta/file
    def __init__(self,
                 chassis=None,
                 license_server=None,
                 system_data=None,
                 spirent_lib_path=None,
                 spirent_tcl_bin=None):
        """
        Spirent abstraction layer for HLTAPI

        -- Workflow 1 --
        :param  system_data:  *MANDATORY* Dictionary of Spirent information
          rt0:
            interfaces:
              intf1:
                name: 1/8
              intf2:
                name: 1/9
            system:
              primary:
                appserver: wf-appserver2.englab.juniper.net
                controllers:
                  unknown:
                    domain: englab.juniper.net
                    hostname: wf-ixchassis2
                    mgt-intf-name: mgt0
                    mgt-ip: 10.9.1.107
                    osname: IxOS
                license_server: sv8-pod1-ixlic1.englab.juniper.net
                make: spirent
                model: xgs12
                name: wf-ixchassis2
                osname: IxOS

        -- Workflow 2 --
        :param  host  *MANDATORY* FQDN/mgt-ip of of chassis
        :param  labserver  *OPTIONAL* FQDN/mgt-ip of of lab server
        :param  license_server *OPTIONAL* FQDN/mgt-ip of license server


        :return: Spirent object
        """

        self.debug = False
        self.virtual = False
        self.port_list = None
        self.port_order = None
        self.license_server = None
        self.chassis = None
        self.labserver = None
        self.labserver_session_name = 'toby' + str(
            random.randrange(1000, 9999, 1))
        self.labserver_preserve_session = False
        self.labserver_create_new_session = 1
        self.is_labserver_connected = False
        self.intf_to_port_map = None
        self.port_to_handle_map = None
        self.session_info = None
        self.config_file = None
        self.handle_to_port_map = None
        self.log_dir = get_log_dir()
        atexit.register(self.cleanup)
        self.sth = None
        self.user_functions = dict()
        self.username, self.password = credentials.get_credentials(
            os='Spirent')
        self.read_timeout = 60
        self.tcl = None
        self.tcl32 = None
        self.tcl64 = None

        if spirent_lib_path and spirent_tcl_bin:
            self.lib_path = spirent_lib_path
            self.tcl = spirent_tcl_bin
        else:
            environment = yaml.safe_load(
                open(
                    os.path.join(os.path.dirname(credentials.__file__),
                                 "environment.yaml")))
            self.lib_path = environment['spirent-lib-path']
            self.tcl32 = environment['tcl32-bin']
            self.tcl64 = environment['tcl64-bin']

        if system_data:
            controller_key = list(
                system_data['system']['primary']['controllers'].keys())[0]

            if 'user' in system_data['system']['primary']['controllers'][controller_key] and \
                system_data['system']['primary']['controllers'][controller_key]['user']:
                self.username = system_data['system']['primary'][
                    'controllers'][controller_key]['user']
            if 'password' in system_data['system']['primary']['controllers'][controller_key] and \
                system_data['system']['primary']['controllers'][controller_key]['password']:
                self.password = system_data['system']['primary'][
                    'controllers'][controller_key]['password']

            kwargs = dict()
            kwargs['host'] = self.chassis = system_data['system']['primary'][
                'name']
            kwargs['hostname'] = self.chassis = system_data['system'][
                'primary']['name']
            kwargs['os'] = system_data['system']['primary']['controllers'][
                controller_key]['osname']
            kwargs['user'] = self.username
            kwargs['password'] = self.password
            super(Spirent, self).__init__(**kwargs)

            if 'labserver' in system_data['system']['primary']:
                self.labserver = system_data['system']['primary']['labserver']
                try:
                    ipaddress.ip_address(self.labserver)
                except Exception:
                    self.labserver = socket.gethostbyname(self.labserver)
                if 'labserver_session_name' in system_data['system'][
                        'primary']:
                    self.labserver_session_name = system_data['system'][
                        'primary']['labserver_session_name']
                    if 'labserver_connect_existing_session' in system_data[
                            'system']['primary']:
                        self.labserver_create_new_session = 0
                if 'labserver_preserve_session' in system_data['system'][
                        'primary']:
                    self.log("Preserving labserver session")
                    self.labserver_preserve_session = True
            if 'config-file' in system_data['system']['primary']:
                self.config_file = str(
                    system_data['system']['primary']['config-file'])
            if 'port-order' in system_data['system']['primary']:
                self.port_order = system_data['system']['primary'][
                    'port-order']
            if 'debug' in system_data['system']['primary']:
                self.debug = system_data['system']['primary']['debug']
            if 'mgt-ip' in system_data['system']['primary']['controllers'][
                    controller_key]:
                self.chassis = system_data['system']['primary']['controllers'][
                    controller_key]['mgt-ip']

            if system_data['system']['primary']['model'].upper() == 'VSPIRENT':
                self.virtual = True
                try:
                    self.license_server = system_data['system']['primary'][
                        'license_server']
                except:
                    raise TobyException(
                        "Missing license_server 'primary' stanza: " +
                        str(system_data),
                        host_obj=self)

        elif chassis:
            self.chassis = chassis
            if license_server:
                self.license_server = license_server
        else:
            raise TobyException(
                "Missing either system_data (Workflow 1) or chassis (Workflow 2) parameter",
                host_obj=self)

        if not self.chassis:
            raise TobyException(
                "Unable to determine chassis host information! Check for valid labserver or mgt-ip in init yaml file.",
                host_obj=self)

        self.connect_info = None
        self.log("CHASSIS= " + str(self.chassis))

        self.wait = 1
        self.telnet_handle = None
        self.version = self._get_version()
        self.hltapi_lib_path = None

        if 'hltapi-path' in system_data['system']['primary']:
            self.hltapi_lib_path = system_data['system']['primary'][
                'hltapi-path']
            self.hltapi_lib_path.rstrip('/')
        else:
            hltapi_version = self._get_hltapi_version()
            self.hltapi_lib_path = self.lib_path + '/HLTAPI/' + hltapi_version

        sys.path.append(self.hltapi_lib_path + '/SourceCode/hltapiForPython')

        self._set_envs()
        #resetting sys.argv[0] is only way to get spirent htlapi logs to go to the right place
        executable = sys.argv[0]
        sys.argv[0] = self.log_dir
        self.sth = __import__('sth')
        sys.argv[0] = executable
        self.log("Spirent Chassis Initialization Complete")

        # Import extended spirent modules with functions from jnpr/toby/trafficgen/spirent
        current_dir = os.path.dirname(
            os.path.abspath(inspect.getfile(inspect.currentframe())))
        user_module_dir = re.sub(r"jnpr\/toby.*",
                                 "jnpr/toby/trafficgen/spirent", current_dir)
        sys.path.append(user_module_dir)
        file_list = list(
            filter(lambda x: os.path.isfile(os.path.join(user_module_dir, x)),
                   os.listdir(user_module_dir)))
        for file_name in file_list:
            if file_name.endswith('.py') and not file_name.startswith('__'):
                module = re.sub(r"\.py$", "", file_name)
                obj = __import__(module)
                function_list = [
                    o for o in inspect.getmembers(obj)
                    if inspect.isfunction(o[1])
                ]
                for function_tuple in function_list:
                    function_name, function = function_tuple
                    if function_name in self.user_functions:
                        raise TobyException(
                            "Duplicate functions in user contributed modules",
                            host_obj=self)
                    self.user_functions[function_name] = function
예제 #11
0
파일: unix.py 프로젝트: SrijaGupta/file
    def __new__(cls, **kvargs):
        """
        Static method that returns a device object of class CentOS, FreeBSD, or
        Ubuntu.
        :param host:
            **REQUIRED** hostname or IP address of device to telnet to
        :param user:
            *OPTIONAL* Login user name. If not provided will be derived from
            Toby framework defaults.
        :param password:
            *OPTIONAL* Login Password. If not provided will be derived from
            Toby framework defaults.
        :param connect_mode:
            *OPTIONAL* Connection mode to device. Default is ssh. Supported
            values are telnet/ssh
        :param model:
            *OPTIONAL* Unix model of device to connect
        :return: Device object based on os and model

        """

        if 'host' not in kvargs:
            raise TobyException("Mandatory Parameter host missing")
        #username and password are not specified by caller
        if not kvargs['user']:
            kvargs['user'], kvargs['password'] = credentials.get_credentials(
                os=kvargs['osname'])

        if kvargs.get('connect_targets') == "console":
            host = kvargs.get('con-ip')
        else:
            host = kvargs.get('host')

        connect_mode = kvargs.get('connect_mode', 'ssh')
        cls.handle = ''
        # returns appropiate handle for device connection
        cls.handle = _connect_unix(kvargs)

        if connect_mode == 'ssh':
            kvargs['port'] = 22
            tnh = cls.handle.client
            try:
                if tnh.recv_ready():
                    tnh.in_buffer.empty()
                tnh.send('uname -sr\n')
                time.sleep(1)
            except Exception as exp:
                message = "Failed to send command '%s' to %s: %s" % (
                    'uname -sr', host, exp.__str__())
                raise TobyConnectLost(message=message)
            got = ''
            while True:
                read, write, err = select([tnh], [], [], 10)
                if read:
                    data = tnh.recv(1024)
                    data = data.decode("utf-8")
                    got = got + data
                    if re.search(r'(\$|>|#|%)[\s\t]?$', data):
                        break
            if re.search('FreeBSD', got, flags=re.IGNORECASE):
                unix_flavour = 'FreeBSD'
            elif re.search('Linux', got, flags=re.IGNORECASE):
                unix_flavour = 'CentOS'
            else:
                if 'model' in kvargs:
                    unix_flavour = kvargs['model']
                else:
                    unix_flavour = 'Unknown'
            if 'model' in kvargs and kvargs['model'] == 'sifos':
                unix_flavour = 'Sifos'
        else:
            kvargs['port'] = 23
            unix_flavour = cls._get_unix_flavour(cls)

        if 'model' in kvargs:
            kvargs['unix_flavour'] = kvargs['model']

        if unix_flavour:
            if unix_flavour.upper() == 'CENTOS':
                unix_handle = CentOS(handle=cls.handle, **kvargs)
            elif unix_flavour.upper() == 'FREEBSD':
                unix_handle = FreeBSD(handle=cls.handle, **kvargs)
            elif unix_flavour.upper() == 'UBUNTU':
                unix_handle = UnixHost(handle=cls.handle, **kvargs)
            elif unix_flavour.upper() == 'LINUX':
                unix_handle = UnixHost(handle=cls.handle, **kvargs)
            elif unix_flavour.upper() == 'SIFOS':
                unix_handle = Sifos(handle=cls.handle, **kvargs)
                return unix_handle
            else:
                raise TobyException("Invalid Unix model detected: '%s'" %
                                    unix_flavour)
        else:
            raise TobyException("Invalid Unix model detected: '%s'" %
                                unix_flavour)

        prompt = 'Toby-%s-%s%% ' % (os.getpid(), unix_handle.host)
        unix_handle.set_prompt(prompt)
        return unix_handle