<commit_before>"""
This file defines the 'netconifyCmdo' class.
Used by the 'netconify' shell utility.
"""
import os
import json
import warnings
import traceback
from lxml import etree

from jnpr.junos.transport.tty_telnet import Telnet
from jnpr.junos.transport.tty_ssh import SecureShell
from jnpr.junos.transport.tty_serial import Serial
from jnpr.junos.rpcmeta import _RpcMetaExec
from jnpr.junos import exception as EzErrors


QFX_MODEL_LIST = ['QFX3500', 'QFX3600', 'VIRTUAL CHASSIS']
QFX_MODE_NODE = 'NODE'
QFX_MODE_SWITCH = 'SWITCH'


class Console(object):

    # ------------------------------------------------------------------------
    # property: hostname
    # ------------------------------------------------------------------------

    @property
    def hostname(self):
        """
        :returns: the host-name of the Junos device.
        """
        return self._hostname

    # ------------------------------------------------------------------------
    # property: user
    # ------------------------------------------------------------------------

    @property
    def user(self):
        """
        :returns: the login user (str) accessing the Junos device
        """
        return self._auth_user

    # ------------------------------------------------------------------------
    # property: password
    # ------------------------------------------------------------------------

    @property
    def password(self):
        """
        :returns: ``None`` - do not provide the password
        """
        return None  # read-only

    @password.setter
    def password(self, value):
        """
        Change the authentication password value.  This is handy in case
        the calling program needs to attempt different passwords.
        """
        self._auth_password = value

    # ------------------------------------------------------------------------
    # property: port
    # ------------------------------------------------------------------------

    @property
    def port(self):
        """
        :returns: the port (str) to connect to the Junos device
        """
        return self._port

    # ------------------------------------------------------------------------
    # property: facts
    # ------------------------------------------------------------------------

    @property
    def facts(self):
        """
        :returns: Device fact dictionary
        """
        return self._facts

    @facts.setter
    def facts(self, value):
        """ read-only property """
        raise RuntimeError("facts is read-only!")

    def __init__(self, *args, **kvargs):
        """
        NoobDevice object constructor.

        :param str host:
            **REQUIRED** host-name or ipaddress of target device

        :param str user:
            *OPTIONAL* login user-name, uses $USER if not provided

        :param str passwd:
            *OPTIONAL* if not provided, assumed ssh-keys are enforced

        :param int port:
            *OPTIONAL*  port

        :param bool gather_facts:
            *OPTIONAL* default is ``True``.  If ``False`` then the
            facts are not gathered on call to :meth:`open`

        """

        # ----------------------------------------
        # setup instance connection/open variables
        # ----------------------------------------

        self._tty = None
        self._facts = {}
        self.connected = False
        self._skip_logout = False
        self.on_notify = kvargs.get('notify', None)
        self.results = dict(changed=False, failed=False, errmsg=None)

        self._hostname = kvargs.get('host')
        if self._hostname is None:
            raise ValueError("You must provide the 'host' value")

        self._auth_user = kvargs.get('user', 'root')
        self._auth_password = kvargs.get('password') or kvargs.get('passwd')
        self._port = kvargs.get('port', '/dev/ttyUSB0')
        self._baud = kvargs.get('baud', '9600')
        self._mode = kvargs.get('mode', 'telnet')
        self._timeout = kvargs.get('timeout', '0.5')
        self._attempts = kvargs.get('attempts', 10)
        self.gather_facts = kvargs.get('gather_facts', False)
        self.rpc = _RpcMetaExec(self)

    def open(self):
        """
        open the connection to the device
        """

        # ---------------------------------------------------------------
        # validate device hostname or IP address
        # ---------------------------------------------------------------

        if self._hostname is None:
             self.results['failed'] = True
             self.results['errmsg'] = 'ERROR: Device hostname/IP not specified !!!'
             return self.results

        # --------------------
        # login to the CONSOLE
        # --------------------

        try:
            self._tty_login()
        except Exception as err:
            self._hook_exception('login', err)
            traceback.print_exc()
        self.connected = True


        if self.gather_facts is True:
            self._gather_facts()

        return self


    def close(self, skip_logout = True):
        """
        Closes the connection to the device.
        """
        if skip_logout is False and self.connected is True:
            try:
                self._tty_logout()
            except Exception as err:
                self._hook_exception('logout', err)
            self.connected = False
        elif self.connected is True:
            try:
                self._tty._tty_close()
            except Exception as err:
                self._hook_exception('close', err)
                traceback.print_exc()
            self.connected = False

    def cli(self, command, format='text', warning=True):
        """
        Executes the CLI command and returns the CLI text output by default.<commit_msg>logging out device before closing<commit_after>"""
This file defines the 'netconifyCmdo' class.
Used by the 'netconify' shell utility.
"""
import os
import json
import warnings
import traceback
from lxml import etree

from jnpr.junos.transport.tty_telnet import Telnet
from jnpr.junos.transport.tty_ssh import SecureShell
from jnpr.junos.transport.tty_serial import Serial
from jnpr.junos.rpcmeta import _RpcMetaExec
from jnpr.junos import exception as EzErrors


QFX_MODEL_LIST = ['QFX3500', 'QFX3600', 'VIRTUAL CHASSIS']
QFX_MODE_NODE = 'NODE'
QFX_MODE_SWITCH = 'SWITCH'


class Console(object):

    # ------------------------------------------------------------------------
    # property: hostname
    # ------------------------------------------------------------------------

    @property
    def hostname(self):
        """
        :returns: the host-name of the Junos device.
        """
        return self._hostname

    # ------------------------------------------------------------------------
    # property: user
    # ------------------------------------------------------------------------

    @property
    def user(self):
        """
        :returns: the login user (str) accessing the Junos device
        """
        return self._auth_user

    # ------------------------------------------------------------------------
    # property: password
    # ------------------------------------------------------------------------

    @property
    def password(self):
        """
        :returns: ``None`` - do not provide the password
        """
        return None  # read-only

    @password.setter
    def password(self, value):
        """
        Change the authentication password value.  This is handy in case
        the calling program needs to attempt different passwords.
        """
        self._auth_password = value

    # ------------------------------------------------------------------------
    # property: port
    # ------------------------------------------------------------------------

    @property
    def port(self):
        """
        :returns: the port (str) to connect to the Junos device
        """
        return self._port

    # ------------------------------------------------------------------------
    # property: facts
    # ------------------------------------------------------------------------

    @property
    def facts(self):
        """
        :returns: Device fact dictionary
        """
        return self._facts

    @facts.setter
    def facts(self, value):
        """ read-only property """
        raise RuntimeError("facts is read-only!")

    def __init__(self, *args, **kvargs):
        """
        NoobDevice object constructor.

        :param str host:
            **REQUIRED** host-name or ipaddress of target device

        :param str user:
            *OPTIONAL* login user-name, uses $USER if not provided

        :param str passwd:
            *OPTIONAL* if not provided, assumed ssh-keys are enforced

        :param int port:
            *OPTIONAL*  port

        :param bool gather_facts:
            *OPTIONAL* default is ``True``.  If ``False`` then the
            facts are not gathered on call to :meth:`open`

        """

        # ----------------------------------------
        # setup instance connection/open variables
        # ----------------------------------------

        self._tty = None
        self._facts = {}
        self.connected = False
        self._skip_logout = False
        self.on_notify = kvargs.get('notify', None)
        self.results = dict(changed=False, failed=False, errmsg=None)

        self._hostname = kvargs.get('host')
        if self._hostname is None:
            raise ValueError("You must provide the 'host' value")

        self._auth_user = kvargs.get('user', 'root')
        self._auth_password = kvargs.get('password') or kvargs.get('passwd')
        self._port = kvargs.get('port', '/dev/ttyUSB0')
        self._baud = kvargs.get('baud', '9600')
        self._mode = kvargs.get('mode', 'telnet')
        self._timeout = kvargs.get('timeout', '0.5')
        self._attempts = kvargs.get('attempts', 10)
        self.gather_facts = kvargs.get('gather_facts', False)
        self.rpc = _RpcMetaExec(self)

    def open(self):
        """
        open the connection to the device
        """

        # ---------------------------------------------------------------
        # validate device hostname or IP address
        # ---------------------------------------------------------------

        if self._hostname is None:
             self.results['failed'] = True
             self.results['errmsg'] = 'ERROR: Device hostname/IP not specified !!!'
             return self.results

        # --------------------
        # login to the CONSOLE
        # --------------------

        try:
            self._tty_login()
        except Exception as err:
            self._hook_exception('login', err)
            traceback.print_exc()
        self.connected = True


        if self.gather_facts is True:
            self._gather_facts()

        return self


    def close(self, skip_logout = False):
        """
        Closes the connection to the device.
        """
        if skip_logout is False and self.connected is True:
            try:
                self._tty_logout()
            except Exception as err:
                self._hook_exception('logout', err)
            self.connected = False
        elif self.connected is True:
            try:
                self._tty._tty_close()
            except Exception as err:
                self._hook_exception('close', err)
                traceback.print_exc()
            self.connected = False

    def cli(self, command, format='text', warning=True):
        """
        Executes the CLI command and returns the CLI text output by default.
{'fraction_non_alphanumeric': 0.24784206478078796, 'fraction_numerical': 0.0029057345526023416, 'mean_word_length': 1.2008651495204063, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 2}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1846832', 'n_tokens_mistral': 2870, 'n_tokens_neox': 2743, 'n_words': 795}