Ejemplo n.º 1
0
def main():
    ip_addr = '50.76.53.27'
    port_rtr1 = 22
    port_rtr2 = 8022
    username = '******'
    password = '******'
    #password = getpass()
    
    pynet1 = {
        'device_type': 'cisco_ios',
        'ip': ip_addr,
        'username': username,
        'password': password,
        'port': port_rtr1,
    }

    pynet_rtr1 = ConnectHandler(**pynet1)

    pynet_rtr1.find_prompt()    

    print "we are getting into config mode"
    pynet_rtr1.config_mode()

    if pynet_rtr1.check_config_mode():
        print "yes, we are in config mode"
    else:
        print "sometthing is wrong, we are not in config mode!"
Ejemplo n.º 2
0
def main():
    #password = getpass()
    password = '******'

    # Define libraries for devices we will connect to
    pynet1 = {
        'device_type': 'cisco_ios',
        'ip': '50.76.53.27',
        'username': '******',
        'password': password,
        'port': 22,
    }
    pynet2 = {
        'device_type': 'cisco_ios',
        'ip': '50.76.53.27',
        'username': '******',
        'password': password,
        'port': 8022,
    }
    srx = {
        'device_type': 'juniper',
        'ip': '50.76.53.27',
        'username': '******',
        'password': password,
        'port': 9822,
    }


    pynet_rtr2 = ConnectHandler(**pynet2)
    pynet_rtr2.config_mode()
    outp = pynet_rtr2.find_prompt()
    print outp
    outp2 = pynet_rtr2.check_config_mode()
    print 'Config mode status is ' + str(outp2)
Ejemplo n.º 3
0
def main():

    password = getpass()

    py_router_2 = {
                'device_type':'cisco_ios',
                'ip':'50.76.53.27',
                'username':'******',
                'password':password,
                'port':8022,
    }

    rtr2 = ConnectHandler(**py_router_2)
    rtr2.config_mode()
    output = rtr2.check_config_mode()
    print "RTR Config mode is %s" % output

    if (output is True):
        #config_command = ['loggin buffered 5555']
        #output = rtr2.send_config_set(config_command)
        output = rtr2.send_config_from_file(config_file='config_file.txt')
        print "Changes send to router.\n %s" % output
        rtr2.exit_config_mode()
    else:
        print "Could not get to config mode.\n"
Ejemplo n.º 4
0
def main():
    username = '******'
    password = '******'
    pynet1 = {
        'device_type': 'cisco_ios',
        'ip': '50.76.53.27',
        'username': username,
        'password': password,
        'port': 22,
    }
    pynet2 = {
        'device_type': 'cisco_ios',
        'ip': '50.76.53.27',
        'username': username,
        'password': password,
        'port': 8022,
    }
    juniper_srx = {
        'device_type': 'juniper',
        'ip': '50.76.53.27',
        'username': username,
        'password': password,
        'secret': '',
        'port': 9822,
    }


    pynet_rtr2 = ConnectHandler( **pynet2 )

    pynet_rtr2.config_mode()

    if pynet_rtr2.check_config_mode() :
        print "We are in config mode for pynet rtr2"
    else:
        print "No config mode for pynet rtr2"
Ejemplo n.º 5
0
def main():
    password = getpass
    pynet_rtr2 = ConnectHandler(**pynet2)
    pynet_rtr2.config_mode()
    if pynet_rtr2.check_config_mode(): 
        print "You are in config mode.\n"
    else:  
        print "Config mode failed.\n"
def main():
    '''Main function, opens connection, enters config mode and verifies'''
    pynet_rtr1 = ConnectHandler(**device_list.RTR1)
    pynet_rtr1.config_mode()
    if pynet_rtr1.check_config_mode():
        print "We are in Config mode"
    else:
        print "We are NOT in Config mode"
def main():
    '''Main function, opens connection, enters config mode, changes logging
    and verifies'''
    pynet_rtr2 = ConnectHandler(**RTR2)
    pynet_rtr2.config_mode()
    if pynet_rtr2.check_config_mode():
        pynet_rtr2.send_command("logging buffered 16384")
        pynet_rtr2.exit_config_mode()
        output = pynet_rtr2.send_command("show run | include logging buff")
        print output
    else:
        print "We are NOT in Config mode"
Ejemplo n.º 8
0
def main():
    '''
    Use Netmiko to enter into configuration mode on pynet-rtr2. Also use Netmiko
    to verify your state (i.e. that you are currently in configuration mode).
    '''

    pynet_rtr2 = ConnectHandler(**pynet2)
    pynet_rtr2.config_mode()
    output = pynet_rtr2.check_config_mode()
    print
    print 'Checking to see if we are in config mode:'
    print output
    print
Ejemplo n.º 9
0
def main():

    my_device = {
        'device_type': 'cisco_ios',
        'ip': '10.40.0.1',
        'username': '******',
        'password': '******'
    }

    # Connect to device
    device_conn = ConnectHandler(**my_device)

    # Enter Config mode
    device_conn.config_mode()

    # Verify current mode
    print device_conn.check_config_mode()

    # Print the current prompt
    print device_conn.find_prompt()

    # Close connection
    device_conn.disconnect()
Ejemplo n.º 10
0
def main():


    password = getpass()
    
    for a_dict in (pynet1, pynet2, juniper_srx):
        a_dict['password'] = password
        
    net_connect2 = ConnectHandler(**pynet2)
    net_connect2.config_mode()
    
    
    print "Config mode:{}".format(net_connect2.check_config_mode())
    print "Current prompt: {}".format(net_connect2.find_prompt())
Ejemplo n.º 11
0
Archivo: ex7.py Proyecto: jvalcke/pynet
def main():
    pynet2 = {
        'device_type': 'cisco_ios',
        'ip' : '50.76.53.27',
        'username' : 'pyclass',
        'port' : 8022,
        'password' : '88newclass'
    }

    pynet_rtr2 = ConnectHandler(**pynet2)
    pynet_rtr2.config_mode() 
    if pynet_rtr2.check_config_mode():
        print "We're in config mode"
        pynet_rtr2.send_command("logging buffered 33333")
    else:
        print "Nope, We're  NOT in config mode"
Ejemplo n.º 12
0
def main():
    '''
    Connects to router and switches to config mode
    '''
    pynet_rtr2 = ConnectHandler(**pynet2)
    pynet_rtr2.enable()
    pynet_rtr2.config_mode()
    
    '''
    Checks to see if you are in enable mode and prints results to screen
    '''
    if pynet_rtr2.check_config_mode() is True:
        output = pynet_rtr2.find_prompt()
        print output
    else:
        print 'You are NOT in config mode'
Ejemplo n.º 13
0
def main():
    '''
    Using Netmiko enter into configuration mode on a network device.

    Verify that you are currently in configuration mode.
    '''
    password = getpass()

    for a_dict in (pynet1, pynet2, juniper_srx):
        a_dict['password'] = password
    net_connect2 = ConnectHandler(**pynet2)
    net_connect2.config_mode()
    print "\n>>>>"
    print "Checking pynet-rtr2 is in configuration mode."
    print "Config mode check: {}".format(net_connect2.check_config_mode())
    print "Current prompt: {}".format(net_connect2.find_prompt())
    print ">>>>\n"
Ejemplo n.º 14
0
def main():

    password = getpass()

    py_router_2 = {
                'device_type':'cisco_ios',
                'ip':'50.76.53.27',
                'username':'******',
                'password':password,
                'port':8022,
    }

    rtr2 = ConnectHandler(**py_router_2)
    rtr2.config_mode()
    output = rtr2.check_config_mode()
    print "RTR Config mode is %s" % output

    rtr2.exit_config_mode()
Ejemplo n.º 15
0
def main():
    '''
    Use Netmiko to enter into configuration mode on pynet-rtr2. Also use
    Netmiko to verify your state (i.e. that you are currently in configuration mode).
    '''

    ip_address = raw_input("Please enter IP: ")
    password = getpass()

    pynet_rtr2['ip'] = ip_address
    pynet_rtr2['password'] = password

    ssh_conn = ConnectHandler(**pynet_rtr2)

    ssh_conn.config_mode()

    if ssh_conn.check_config_mode():
        print "In config mode"
Ejemplo n.º 16
0
Archivo: ex5.py Proyecto: jvalcke/pynet
def main():
    pynet2 = {
        'device_type': 'cisco_ios',
        'ip' : '50.76.53.27',
        'username' : 'pyclass',
        'port' : 8022,
        'password' : '88newclass'
    }

    pynet_rtr2 = ConnectHandler(**pynet2)
    pynet_rtr2.config_mode() 
    if pynet_rtr2.check_config_mode():
        print "We're in config mode"
    else:
        print "Nope, We're  NOT in config mode"
    print pynet_rtr2.find_prompt() 
    pynet_rtr2.exit_config_mode() 
    print pynet_rtr2.find_prompt() 
Ejemplo n.º 17
0
def main():
    '''
    Using Netmiko enter into configuration mode on a network device.
    Verify that you are currently in configuration mode.
    '''

    ip_addr = raw_input("Enter IP Address: ")
    password = getpass()
    
    for a_dict in (pynet1, pynet2, juniper_srx):
        a_dict['ip'] = ip_addr
        a_dict['password'] = password

    pynet_rtr2 = ConnectHandler(**pynet2)

    pynet_rtr2.config_mode()

    print "\n>>>>"
    print "Checking pynet-rtr2 is in configuration mode"
    print "Config mode check: {}".format(pynet_rtr2.check_config_mode())
    print "Current prompt: {}".format(pynet_rtr2.find_prompt())
    print ">>>>\n"
Ejemplo n.º 18
0
def main():

    password = getpass()

    pynet1 = {
        'device_type': 'cisco_ios',
        'ip': '50.76.53.27',
        'username': '******',
        'password': password,
    }

    pynet2 = {
        'device_type': 'cisco_ios',
        'ip': '50.76.53.27',
        'username': '******',
        'password': password,
        'port': 8022,
    }

    juniper_srx = {
        'device_type': 'juniper',
        'ip': '50.76.53.27',
        'username': '******',
        'password': password,
        'secret': '',
        'port': 9822,
    }

#    pynet_rtr1 = ConnectHandler(**pynet1)
    pynet_rtr2 = ConnectHandler(**pynet2)
    time.sleep(5)
#    srx = ConnectHandler(**juniper_srx)

    pynet_rtr2.config_mode()
    time.sleep(5)
    output = pynet_rtr2.check_config_mode()
    print "\nConfig mode? (true/false):"
    print output
Ejemplo n.º 19
0
def main():
    print 'Username:'******'device_type':DEV_TYPE,
            'ip':dev,
            'username':usern,
            'password':passwd
            }
        # Initiating netmiko connection
        net_connect = ConnectHandler(**net_dev)
        resp = net_connect.find_prompt()
        print resp
        # Entering config mode
        net_connect.config_mode()
        # Verifying we're in config mode
        resp = net_connect.check_config_mode()
        print 'Entered Config mode? {}'.format(resp)
        # Exiting config mode
        net_connect.exit_config_mode()
Ejemplo n.º 20
0
def main():

    # Definition of rtr2.
    rtr2 = {
        'device_type': 'cisco_ios',
        'ip':   '50.76.53.27',
        'username': '******',
        'password': '******',
        'port': 8022,
    }    

    # Log into router.
    net_connect = ConnectHandler(**rtr2)

    # Enter configuration mode.
    output = net_connect.config_mode()

    # Verify whether we are in configuration mode.
    output = net_connect.check_config_mode()
    print
    print "Are we in config mode?"
    print output
    print
def main():
    '''
    Using Netmiko enter into configuation mode on a network device.

    Verify that you are currently in configration mode.
    '''

    ip_addr = raw_input("Enter IP Address: ")
    password = getpass()

    for a_dict in (pynet1, pynet2):
        a_dict['ip'] = ip_addr
        a_dict['password'] = password
    

        net_connect2 = ConnectHandler(**a_dict)
        net_connect2.config_mode()

        print "\n>>>"
        print "Checking {}:{} is in configuration mode.".format(net_connect2.ip, net_connect2.port)
        print "Config mode check: {}".format(net_connect2.check_config_mode())
        print "Current prompt: {}".format(net_connect2.find_prompt())
        print ">>>>\n"
Ejemplo n.º 22
0
from netmiko import ConnectHandler
from getpass import getpass
password = getpass()

NB_3850_8 = {
	'device_type': 'cisco_ios',
	'ip': '50.76.53.27',
	'username' : 'pyclass',
	'password': password,
	'port' : 8022,
}



nick_3850 = ConnectHandler(**NB_3850_8)

nick_3850.find_prompt()
nick_3850.exit_config_mode()
nick_3850.config_mode()
output = nick_3850.check_config_mode()

print 'In configuration mode:' ,  output
Ejemplo n.º 23
0
from netmiko import ConnectHandler
from getpass import getpass
password = getpass()

NB_3850_8 = {
    'device_type': 'cisco_ios',
    'ip': '50.76.53.27',
    'username': '******',
    'password': password,
    'port': 8022,
}

nick_3850 = ConnectHandler(**NB_3850_8)

nick_3850.find_prompt()
nick_3850.exit_config_mode()
nick_3850.config_mode()
output = nick_3850.check_config_mode()

print 'In configuration mode:', output
Ejemplo n.º 24
0
#!/usr/bin/env python
'''Simple script to connect to pynet-rtr2 with Netmiko.
Use Netmiko to enter into configuration mode on pynet-rtr2.
Also use Netmiko to verify that you are in configuration mode.'''
from netmiko import ConnectHandler
from getpass import getpass

password = getpass()

pynet2 = {
    'device_type': 'cisco_ios',
    'ip': '184.105.247.71',
    'username': '******',
    'password': password,
    'port': 22,
    }

pynet_rtr2 = ConnectHandler(**pynet2)

print 10 * '>', 'Show me current prompt:\n', pynet_rtr2.find_prompt(), '\n'
print 10 * '>', 'Enter config mode:\n', pynet_rtr2.config_mode(), '\n'
print 10 * '>', 'Check if you are in config mode:\n', pynet_rtr2.check_config_mode(), '\n'

if pynet_rtr2.check_config_mode() == True:
    print 10 * '_','The config mode prompt is:', 10 * '_', '\n', pynet_rtr2.find_prompt()
else:
   print 'You are not in config mode - try again.'

from netmiko import ConnectHandler

pynet1 = {'device_type': 'cisco_ios','ip': '172.31.33.81','username': '******','password': '******',}

pynet1_rtr = ConnectHandler(**pynet1)

'''
METHODS
>>> dir(pynet1_rtr)
['RESPONSE_RETURN', 'RETURN', 'TELNET_RETURN', '__class__', '__delattr__', '__dict__', '__doc__', '__enter__', '__exit__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_autodetect_fs', '_build_ssh_client', '_connect_params_dict', '_first_line_handler', '_lock_netmiko_session', '_modify_connection_params', '_read_channel', '_read_channel_expect', '_read_channel_timing', '_sanitize_output', '_session_locker', '_session_log_close', '_session_log_fin', '_test_channel_read', '_timeout_exceeded', '_try_session_preparation', '_unlock_netmiko_session', '_use_ssh_config', '_write_channel', '_write_session_log', 'allow_agent', 'allow_auto_change', 'alt_host_keys', 'alt_key_file', 'ansi_escape_codes', 'auth_timeout', 'base_prompt', 'blocking_timeout', 'check_config_mode', 'check_enable_mode', 'cleanup', 'clear_buffer', 'close_session_log', 'commit', 'config_mode', 'device_type', 'disable_paging', 'disconnect', 'enable', 'encoding', 'establish_connection', 'exit_config_mode', 'exit_enable_mode', 'fast_cli', 'find_prompt', 'global_delay_factor', 'host', 'ip', 'is_alive', 'keepalive', 'key_file', 'key_policy', 'normalize_cmd', 'normalize_linefeeds', 'open_session_log', 'paramiko_cleanup', 'passphrase', 'password', 'pkey', 'port', 'protocol', 'read_channel', 'read_until_pattern', 'read_until_prompt', 'read_until_prompt_or_pattern', 'remote_conn', 'remote_conn_pre', 'save_config', 'secret', 'select_delay_factor', 'send_command', 'send_command_expect', 'send_command_timing', 'send_config_from_file', 'send_config_set', 'serial_login', 'serial_settings', 'session_log', 'session_log_record_writes', 'session_preparation', 'session_timeout', 'set_base_prompt', 'set_terminal_width', 'special_login_handler', 'ssh_config_file', 'strip_ansi_escape_codes', 'strip_backspaces', 'strip_command', 'strip_prompt', 'system_host_keys', 'telnet_login', 'timeout', 'use_keys', 'username', 'verbose', 'write_channel']
>>> pynet1_rtr.find_prompt()
u'router#'
'''

pynet1_rtr.config_mode()
pynet1_rtr.check_config_mode()
pynet1_rtr.exit_config_mode()
pynet1_rtr.check_config_mode()


outp = pynet1_rtr.send_command('show ip interface brief')
print (outp)

outp = pynet1_rtr.send_command('show version')
print (outp)

#Make configuration changes and show that the changes have been made
config_commands = ['logging buffered 19999', 'no logging console']
output = pynet1_rtr.send_config_set(config_commands)
outp = pynet1_rtr.send_command('show run | inc logging')
print(outp)
Ejemplo n.º 26
0
class CEDriver(NetworkDriver):
    """Napalm driver for HUAWEI CloudEngine."""
    def __init__(self,
                 hostname,
                 username,
                 password,
                 timeout=60,
                 optional_args=None):
        """NAPALM Huawei CloudEngine Handler."""
        self.device = None
        self.hostname = hostname
        self.username = username
        self.password = password
        self.timeout = timeout

        # Get optional arguments
        if optional_args is None:
            optional_args = {}

        # Netmiko possible arguments
        netmiko_argument_map = {
            'port': None,
            'verbose': False,
            'conn_timeout': self.timeout,
            'global_delay_factor': 1,
            'use_keys': False,
            'key_file': None,
            'ssh_strict': False,
            'system_host_keys': False,
            'alt_host_keys': False,
            'alt_key_file': '',
            'ssh_config_file': None,
            'allow_agent': False,
            'keepalive': 30
        }

        # Build dict of any optional Netmiko args
        self.netmiko_optional_args = {
            k: optional_args.get(k, v)
            for k, v in netmiko_argument_map.items()
        }

        self.transport = optional_args.get('transport', 'ssh')
        self.port = optional_args.get('port', 22)

        self.changed = False
        self.loaded = False
        self.backup_file = ''
        self.replace = False
        self.merge_candidate = ''
        self.replace_file = ''
        self.profile = ["ce"]

    def open(self):
        """Open a connection to the device."""
        try:
            if self.transport == 'ssh':
                device_type = 'huawei'
            else:
                raise ConnectionException("Unknown transport: {}".format(
                    self.transport))

            self.device = ConnectHandler(device_type=device_type,
                                         host=self.hostname,
                                         username=self.username,
                                         password=self.password,
                                         **self.netmiko_optional_args)
            # self.device.enable()

        except NetMikoTimeoutException:
            raise ConnectionException('Cannot connect to {}'.format(
                self.hostname))

    def close(self):
        """Close the connection to the device."""
        if self.changed and self.backup_file != "":
            self._delete_file(self.backup_file)
        self.device.disconnect()
        self.device = None

    def is_alive(self):
        """Return a flag with the state of the SSH connection."""
        null = chr(0)
        try:
            if self.device is None:
                return {'is_alive': False}
            else:
                # Try sending ASCII null byte to maintain the connection alive
                self.device.send_command(null)
        except (socket.error, EOFError):
            # If unable to send, we can tell for sure that the connection is unusable,
            # hence return False.
            return {'is_alive': False}
        return {'is_alive': self.device.remote_conn.transport.is_active()}

    def compare_config(self):
        """Compare candidate config with running."""
        if self.loaded:
            if not self.replace:
                return self._get_merge_diff()
                # return self.merge_candidate
            diff = self._get_diff(self.replace_file.split('/')[-1])
            return diff
        return ''

    def discard_config(self):
        """Discard changes."""
        if self.loaded:
            self.merge_candidate = ''  # clear the buffer
        if self.loaded and self.replace:
            self._delete_file(self.replace_file)
        self.loaded = False

    def get_facts(self):
        """Return a set of facts from the devices."""
        # default values.
        vendor = u'Huawei'
        uptime = -1
        serial_number, fqdn, os_version, hostname, model = (u'Unknown',
                                                            u'Unknown',
                                                            u'Unknown',
                                                            u'Unknown',
                                                            u'Unknown')

        # obtain output from device
        show_ver = self.device.send_command('display version')
        show_hostname = self.device.send_command(
            'display current-configuration | inc sysname')
        show_int_status = self.device.send_command('display interface brief')

        # serial_number/IOS version/uptime/model
        for line in show_ver.splitlines():
            if 'VRP (R) software' in line:
                search_result = re.search(
                    r"\((?P<serial_number>CE\S+)\s+(?P<os_version>V\S+)\)",
                    line)
                if search_result is not None:
                    serial_number = search_result.group('serial_number')
                    os_version = search_result.group('os_version')

            if 'HUAWEI' in line and 'uptime is' in line:
                search_result = re.search(r"CE\S+", line)
                if search_result is not None:
                    model = search_result.group(0)
                uptime = self._parse_uptime(line)
                break

        if 'sysname ' in show_hostname:
            _, hostname = show_hostname.split("sysname ")
            hostname = hostname.strip()

        # interface_list filter
        interface_list = []
        if 'Interface' in show_int_status:
            _, interface_part = show_int_status.split("Interface")
            re_intf = r"(?P<interface>\S+)\s+(?P<physical_state>down|up|offline|\*down)\s+" \
                      r"(?P<protocal_state>down|up|\*down)"
            search_result = re.findall(re_intf, interface_part, flags=re.M)
            for interface_info in search_result:
                interface_list.append(interface_info[0])

        return {
            'uptime': int(uptime),
            'vendor': vendor,
            'os_version': str(os_version),
            'serial_number': str(serial_number),
            'model': str(model),
            'hostname': str(hostname),
            'fqdn': fqdn,  # ? fqdn(fully qualified domain name)
            'interface_list': interface_list
        }

    def cli(self, commands):
        """Execute raw CLI commands and returns their output."""
        cli_output = {}
        if type(commands) is not list:
            raise TypeError('Please enter a valid list of commands!')

        for command in commands:
            output = self.device.send_command(command)
            cli_output[str(command)] = output
        return cli_output

    def commit_config(self):
        """Commit configuration."""
        if self.loaded:
            try:
                self.backup_file = 'config_' + datetime.now().strftime(
                    "%Y%m%d_%H%M") + '.cfg'
                if self._check_file_exists(self.backup_file):
                    self._delete_file(self.backup_file)
                self._save_config(self.backup_file)
                if self.replace:
                    self._load_config(self.replace_file.split('/')[-1])
                else:
                    self._commit_merge()
                    self.merge_candidate = ''  # clear the merge buffer

                self.changed = True
                self.loaded = False
                self._save_config()
            except Exception as e:
                raise CommitError(str(e))
        else:
            raise CommitError('No config loaded.')

    def load_merge_candidate(self, filename=None, config=None):
        """Open the candidate config and merge."""
        if not filename and not config:
            raise MergeConfigException(
                'filename or config param must be provided.')

        self.merge_candidate += '\n'  # insert one extra line
        if filename is not None:
            with open(filename, "r") as f:
                self.merge_candidate += f.read()
        else:
            self.merge_candidate += config

        self.replace = False
        self.loaded = True

    def load_replace_candidate(self, filename=None, config=None):
        """Open the candidate config and replace."""
        if not filename and not config:
            raise ReplaceConfigException(
                'filename or config param must be provided.')

        self._replace_candidate(filename, config)
        self.replace = True
        self.loaded = True

    def get_interfaces(self):
        """
        Get interface details (last_flapped is not implemented).

        Sample Output:
        {
            "Vlanif3000": {
                "is_enabled": false,
                "description": "",
                "last_flapped": -1.0,
                "is_up": false,
                "mac_address": "0C:45:BA:7D:83:E6",
                "speed": 1000,
                'mtu': 1500
            },
            "Vlanif100": {
                "is_enabled": false,
                "description": "",
                "last_flapped": -1.0,
                "is_up": false,
                "mac_address": "0C:45:BA:7D:83:E4",
                "speed": 1000,
                'mtu': 1500
            }
        }
        """
        interfaces = {}
        output = self.device.send_command('display interface')
        if not output:
            return {}

        separator = r"(^(?!Line protocol).*current state.*$)"
        re_intf_name_state = r"^(?!Line protocol)(?P<intf_name>\S+).+current state\W+(?P<intf_state>.+)$"
        re_protocol = r"Line protocol current state\W+(?P<protocol>.+)$"
        re_mac = r"Hardware address is\W+(?P<mac_address>\S+)"
        re_speed = r"^Speed\W+(?P<speed>\d+|\w+)"
        re_description = r"^Description:(?P<description>.*)$"
        re_mtu = r"(Maximum Transmit Unit|Maximum Frame Length) is (?P<mtu>\d+)"

        new_interfaces = self._separate_section(separator, output)
        for interface in new_interfaces:
            interface = interface.strip()
            match_intf = re.search(re_intf_name_state, interface, flags=re.M)
            match_proto = re.search(re_protocol, interface, flags=re.M)

            if match_intf is None or match_proto is None:
                msg = "Unexpected interface format: {}".format(interface)
                raise ValueError(msg)
            intf_name = match_intf.group('intf_name')
            intf_state = match_intf.group('intf_state')
            is_enabled = bool('up' in intf_state.lower())

            protocol = match_proto.group('protocol')
            is_up = bool('up' in protocol.lower())

            match_mac = re.search(re_mac, interface, flags=re.M)
            if match_mac:
                mac_address = match_mac.group('mac_address')
                mac_address = napalm.base.helpers.mac(mac_address)
            else:
                mac_address = ""

            speed = mtu = 0
            match_speed = re.search(re_speed, interface, flags=re.M)
            if match_speed:
                speed = match_speed.group('speed')
                if speed.isdigit():
                    speed = int(speed)

            match_mtu = re.search(re_mtu, interface, flags=re.M)
            if match_mtu:
                mtu = match_mtu.group('mtu')
                if mtu.isdigit():
                    mtu = int(mtu)

            description = ''
            match = re.search(re_description, interface, flags=re.M)
            if match:
                description = match.group('description').strip()

            interfaces.update({
                intf_name: {
                    'description': description,
                    'is_enabled': is_enabled,
                    'is_up': is_up,
                    'last_flapped': -1.0,
                    'mac_address': mac_address,
                    'speed': speed,
                    'mtu': mtu
                }
            })
        return interfaces

    def get_interfaces_ip(self):
        """
        Get interface IP details. Returns a dictionary of dictionaries.

        Sample output:
        {
            "LoopBack0": {
                "ipv4": {
                    "192.168.0.9": {
                        "prefix_length": 32
                    }
                }
            },
            "Vlanif2000": {
                "ipv4": {
                    "192.168.200.3": {
                        "prefix_length": 24
                    },
                    "192.168.200.6": {
                        "prefix_length": 24
                    },
                    "192.168.200.8": {
                        "prefix_length": 24
                    }
                },
                "ipv6": {
                    "FC00::1": {
                        "prefix_length": 64
                    }
                }
            }
        }
        """
        interfaces_ip = {}
        output_v4 = self.device.send_command('display ip interface')
        output_v6 = self.device.send_command('display ipv6 interface')

        v4_interfaces = {}
        separator = r"(^(?!Line protocol).*current state.*$)"
        new_v4_interfaces = self._separate_section(separator, output_v4)
        for interface in new_v4_interfaces:
            re_intf_name_state = r"^(?!Line protocol)(?P<intf_name>\S+).+current state\W+(?P<intf_state>.+)$"
            re_intf_ip = r"Internet Address is\s+(?P<ip_address>\d+.\d+.\d+.\d+)\/(?P<prefix_length>\d+)"

            match_intf = re.search(re_intf_name_state, interface, flags=re.M)
            if match_intf is None:
                msg = "Unexpected interface format: {}".format(interface)
                raise ValueError(msg)
            intf_name = match_intf.group('intf_name')
            # v4_interfaces[intf_name] = {}
            match_ip = re.findall(re_intf_ip, interface, flags=re.M)

            for ip_info in match_ip:
                val = {'prefix_length': int(ip_info[1])}
                # v4_interfaces[intf_name][ip_info[0]] = val
                v4_interfaces.setdefault(intf_name, {})[ip_info[0]] = val

        v6_interfaces = {}
        separator = r"(^(?!IPv6 protocol).*current state.*$)"
        new_v6_interfaces = self._separate_section(separator, output_v6)
        for interface in new_v6_interfaces:
            re_intf_name_state = r"^(?!IPv6 protocol)(?P<intf_name>\S+).+current state\W+(?P<intf_state>.+)$"
            re_intf_ip = r"(?P<ip_address>\S+), subnet is.+\/(?P<prefix_length>\d+)"

            match_intf = re.search(re_intf_name_state, interface, flags=re.M)
            if match_intf is None:
                msg = "Unexpected interface format: {}".format(interface)
                raise ValueError(msg)
            intf_name = match_intf.group('intf_name')
            match_ip = re.findall(re_intf_ip, interface, flags=re.M)

            for ip_info in match_ip:
                val = {'prefix_length': int(ip_info[1])}
                v6_interfaces.setdefault(intf_name, {})[ip_info[0]] = val

        # Join data from intermediate dictionaries.
        for interface, data in v4_interfaces.items():
            interfaces_ip.setdefault(interface, {'ipv4': {}})['ipv4'] = data

        for interface, data in v6_interfaces.items():
            interfaces_ip.setdefault(interface, {'ipv6': {}})['ipv6'] = data

        return interfaces_ip

    def get_interfaces_counters(self):
        """Return interfaces counters."""
        def process_counts(tup):
            for item in tup:
                if item != "":
                    return int(item)
            return 0

        interfaces = {}
        # command "display interface counters" lacks of some keys
        output = self.device.send_command('display interface')
        if not output:
            return {}

        separator = r"(^(?!Line protocol).*current state.*$)"
        re_intf_name_state = r"^(?!Line protocol)(?P<intf_name>\S+).+current state\W+(?P<intf_state>.+)$"
        re_unicast = r"Unicast:\s+(\d+)|(\d+)\s+unicast"
        re_multicast = r"Multicast:\s+(\d+)|(\d+)\s+multicast"
        re_broadcast = r"Broadcast:\s+(\d+)|(\d+)\s+broadcast"
        re_dicards = r"Discard:\s+(\d+)|(\d+)\s+discard"
        re_rx_octets = r"Input.+\s+(\d+)\sbytes|Input:.+,(\d+)\sbytes"
        re_tx_octets = r"Output.+\s+(\d+)\sbytes|Output:.+,(\d+)\sbytes"
        re_errors = r"Total Error:\s+(\d+)|(\d+)\s+errors"

        new_interfaces = self._separate_section(separator, output)
        for interface in new_interfaces:
            interface = interface.strip()
            match_intf = re.search(re_intf_name_state, interface, flags=re.M)

            if match_intf is None:
                msg = "Unexpected interface format: {}".format(interface)
                raise ValueError(msg)
            intf_name = match_intf.group('intf_name')
            intf_counter = {
                'tx_errors': 0,
                'rx_errors': 0,
                'tx_discards': 0,
                'rx_discards': 0,
                'tx_octets': 0,
                'rx_octets': 0,
                'tx_unicast_packets': 0,
                'rx_unicast_packets': 0,
                'tx_multicast_packets': 0,
                'rx_multicast_packets': 0,
                'tx_broadcast_packets': 0,
                'rx_broadcast_packets': 0
            }

            match = re.findall(re_errors, interface, flags=re.M)
            if match:
                intf_counter['rx_errors'] = process_counts(match[0])
            if len(match) == 2:
                intf_counter['tx_errors'] = process_counts(match[1])

            match = re.findall(re_dicards, interface, flags=re.M)
            if len(match) == 2:
                intf_counter['rx_discards'] = process_counts(match[0])
                intf_counter['tx_discards'] = process_counts(match[1])

            match = re.findall(re_unicast, interface, flags=re.M)
            if len(match) == 2:
                intf_counter['rx_unicast_packets'] = process_counts(match[0])
                intf_counter['tx_unicast_packets'] = process_counts(match[1])

            match = re.findall(re_multicast, interface, flags=re.M)
            if len(match) == 2:
                intf_counter['rx_multicast_packets'] = process_counts(match[0])
                intf_counter['tx_multicast_packets'] = process_counts(match[1])

            match = re.findall(re_broadcast, interface, flags=re.M)
            if len(match) == 2:
                intf_counter['rx_broadcast_packets'] = process_counts(match[0])
                intf_counter['tx_broadcast_packets'] = process_counts(match[1])

            match = re.findall(re_rx_octets, interface, flags=re.M)
            if match:
                intf_counter['rx_octets'] = process_counts(match[0])

            match = re.findall(re_tx_octets, interface, flags=re.M)
            if match:
                intf_counter['tx_octets'] = process_counts(match[0])

            interfaces.update({intf_name: intf_counter})
        return interfaces

    def get_environment(self):
        """
        Return environment details.

        Sample output:
        {
            "cpu": {
                "0": {
                    "%usage": 18.0
                }
            },
            "fans": {
                "FAN1": {
                    "status": true
                }
            },
            "memory": {
                "available_ram": 3884224,
                "used_ram": 784552
            },
            "power": {
                "PWR1": {
                    "capacity": 600.0,
                    "output": 92.0,
                    "status": true
                }
            },
            "temperature": {
                "CPU": {
                    "is_alert": false,
                    "is_critical": false,
                    "temperature": 45.0
                }
            }
        }
        """
        environment = {}

        fan_cmd = 'display device fan'
        power_cmd = 'display device power'
        temp_cmd = 'display device temperature all'
        cpu_cmd = 'display cpu'
        mem_cmd = 'display memory'

        output = self.device.send_command(fan_cmd)
        environment.setdefault('fans', {})
        match = re.findall(r"(?P<id>FAN\S+).+(?P<status>Normal|Abnormal)",
                           output, re.M)
        # if match:
        for fan in match:
            status = True if fan[1] == "Normal" else False
            environment['fans'].setdefault(fan[0], {})['status'] = status

        output = self.device.send_command(power_cmd)
        environment.setdefault('power', {})
        re_power = r"(?P<id>PWR\S+).+(?P<status>Supply|NotSupply|Sleep)\s+\S+\s+\S+\s+" \
                   r"(?P<output>\d+)\s+(?P<capacity>\d+)"
        match = re.findall(re_power, output, re.M)

        for power in match:
            status = True if power[1] == "Supply" else False
            environment['power'].setdefault(power[0], {})['status'] = status
            environment['power'][power[0]]['output'] = float(power[2])
            environment['power'][power[0]]['capacity'] = float(power[3])

        output = self.device.send_command(temp_cmd)
        environment.setdefault('temperature', {})
        re_temp = r"(?P<name>\S+)\s+(?P<status>NORMAL|MAJOR|FATAL|ABNORMAL)\s+\S+\s+\S+\s+(?P<temperature>\d+)"
        match = re.findall(re_temp, output, re.M)

        for temp in match:
            environment['temperature'].setdefault(temp[0], {})
            name = temp[0]
            is_alert = True if temp[1] == "MAJOR" else False
            is_critical = True if temp[1] == "FATAL" else False
            environment['temperature'][name]['temperature'] = float(temp[2])
            environment['temperature'][name]['is_alert'] = is_alert
            environment['temperature'][name]['is_critical'] = is_critical

        output = self.device.send_command(cpu_cmd)
        environment.setdefault('cpu', {})
        match = re.findall(r"cpu(?P<id>\d+)\s+(?P<usage>\d+)%", output, re.M)

        for cpu in match:
            usage = float(cpu[1])
            environment['cpu'].setdefault(cpu[0], {})['%usage'] = usage

        output = self.device.send_command(mem_cmd)
        environment.setdefault('memory', {'available_ram': 0, 'used_ram': 0})
        match = re.search(r"System Total Memory:\s+(?P<available_ram>\d+)",
                          output, re.M)
        if match is not None:
            environment['memory']['available_ram'] = int(
                match.group("available_ram"))

        match = re.search(r"Total Memory Used:\s+(?P<used_ram>\d+)", output,
                          re.M)
        if match is not None:
            environment['memory']['used_ram'] = int(match.group("used_ram"))
        return environment

    def get_arp_table(self, vrf=""):
        """
        Get arp table information.

        Return a list of dictionaries having the following set of keys:
            * interface (string)
            * mac (string)
            * ip (string)
            * age (float)

        Sample output:
            [
                {
                    'interface' : 'MgmtEth0/RSP0/CPU0/0',
                    'mac'       : '5c:5e:ab:da:3c:f0',
                    'ip'        : '172.17.17.1',
                    'age'       : -1
                },
                {
                    'interface': 'MgmtEth0/RSP0/CPU0/0',
                    'mac'       : '66:0e:94:96:e0:ff',
                    'ip'        : '172.17.17.2',
                    'age'       : -1
                }
            ]
        """
        if vrf:
            msg = "VRF support has not been implemented."
            raise NotImplementedError(msg)

        arp_table = []
        output = self.device.send_command('display arp')
        re_arp = r"(?P<ip_address>\d+\.\d+\.\d+\.\d+)\s+(?P<mac>\S+)\s+(?P<exp>\d+|)\s+" \
                 r"(?P<type>I|D|S|O)\s+(?P<interface>\S+)"
        match = re.findall(re_arp, output, flags=re.M)

        for arp in match:
            if arp[2].isdigit():
                exp = round(float(arp[2]) * 60, 1)
            else:
                exp = -1.0

            entry = {
                'interface': arp[4],
                'mac': napalm.base.helpers.mac(arp[1]),
                'ip': arp[0],
                'age': exp
            }
            arp_table.append(entry)
        return arp_table

    def get_config(self, retrieve="all", full=False, sanitized=False):
        """
        Get config from device.

        Returns the running configuration as dictionary.
        The candidate and startup are always empty string for now,
        since CE does not support candidate configuration.
        """
        config = {'startup': '', 'running': '', 'candidate': ''}

        if retrieve.lower() in ('running', 'all'):
            command = 'display current-configuration'
            config['running'] = str(self.device.send_command(command))
        if retrieve.lower() in ('startup', 'all'):
            # command = 'display saved-configuration last'
            # config['startup'] = str(self.device.send_command(command))
            pass
        return config

    def get_lldp_neighbors(self):
        """
        Return LLDP neighbors details.

        Sample output:
        {
            "10GE4/0/1": [
                {
                    "hostname": "HUAWEI",
                    "port": "10GE4/0/25"
                },
                {
                    "hostname": "HUAWEI2",
                    "port": "10GE4/0/26"
                }
            ]
        }
        """
        results = {}
        command = 'display lldp neighbor brief'
        output = self.device.send_command(command)
        re_lldp = r"(?P<local>\S+)\s+\d+\s+(?P<port>\S+)\s+?(?:$|(?P<hostname>\S+).+?$)"
        match = re.findall(re_lldp, output, re.M)
        for neighbor in match:
            local_iface = neighbor[0]
            if local_iface not in results:
                results[local_iface] = []

            neighbor_dict = dict()
            neighbor_dict['port'] = str(neighbor[1])
            neighbor_dict['hostname'] = str(neighbor[2])
            results[local_iface].append(neighbor_dict)
        return results

    def get_mac_address_table(self):
        """
        Return the MAC address table.

        Sample output:
        [
            {
                "active": true,
                "interface": "10GE1/0/1",
                "last_move": -1.0,
                "mac": "00:00:00:00:00:33",
                "moves": -1,
                "static": false,
                "vlan": 100
            },
            {
                "active": false,
                "interface": "10GE1/0/2",
                "last_move": -1.0,
                "mac": "00:00:00:00:00:01",
                "moves": -1,
                "static": true,
                "vlan": 200
            }
        ]
        """
        mac_address_table = []
        command = 'display mac-address'
        output = self.device.send_command(command)
        re_mac = r"(?P<mac>\S+)\s+(?P<vlan>\d+|-)\S*\s+(?P<interface>\S+)\s+(?P<type>\w+)\s+(?P<age>\d+|-)"
        match = re.findall(re_mac, output, re.M)

        for mac_info in match:
            mac_dict = {
                'mac': napalm.base.helpers.mac(mac_info[0]),
                'interface': str(mac_info[2]),
                'vlan': int(mac_info[1]),
                'static': True if mac_info[3] == "static" else False,
                'active': True if mac_info[3] == "dynamic" else False,
                'moves': -1,
                'last_move': -1.0
            }
            mac_address_table.append(mac_dict)
        return mac_address_table

    def get_users(self):
        """
        Return the configuration of the users.

        Sample output:
        {
            "admin": {
                "level": 3,
                "password": "",
                "sshkeys": []
            }
        }
        """
        result = {}
        command = 'display aaa local-user'
        output = self.device.send_command(command)
        re_user = r"(?P<username>\S+)\s+(Active|Block)(\s+\S+){3}\s+(\d+|--)"
        match = re.findall(re_user, output, re.M)
        try:
            for user in match:
                # level = -1 can not pass unit test
                level = 0 if user[3] == '--' else int(user[3])
                result.setdefault(user[0], {})['level'] = level
                result[user[0]]['password'] = ''
                result[user[0]]['sshkeys'] = []
        except Exception:
            msg = "Unexpected output data:\n{}".format(output)
            raise ValueError(msg)

        # Password is encrypted and cannot be read
        # command = 'display current-configuration | inc user'
        # output = self.device.send_command(command)
        return result

    def rollback(self):
        """Rollback to previous commit."""
        if self.changed:
            self._load_config(self.backup_file)
            self.changed = False
            self._save_config()

    def ping(self,
             destination,
             source=c.PING_SOURCE,
             ttl=c.PING_TTL,
             timeout=c.PING_TIMEOUT,
             size=c.PING_SIZE,
             count=c.PING_COUNT,
             vrf=c.PING_VRF):
        """Execute ping on the device."""
        ping_dict = {}
        command = 'ping'
        # Timeout in milliseconds to wait for each reply, the default is 2000
        command += ' -t {}'.format(timeout * 1000)
        # Specify the number of data bytes to be sent
        command += ' -s {}'.format(size)
        # Specify the number of echo requests to be sent
        command += ' -c {}'.format(count)
        if source != '':
            command += ' -a {}'.format(source)
        command += ' {}'.format(destination)
        output = self.device.send_command(command)

        if 'Error' in output:
            ping_dict['error'] = output
        elif 'PING' in output:
            ping_dict['success'] = {
                'probes_sent': 0,
                'packet_loss': 0,
                'rtt_min': 0.0,
                'rtt_max': 0.0,
                'rtt_avg': 0.0,
                'rtt_stddev': 0.0,
                'results': []
            }

            match_sent = re.search(r"(\d+).+transmitted", output, re.M)
            match_received = re.search(r"(\d+).+received", output, re.M)

            try:
                probes_sent = int(match_sent.group(1))
                probes_received = int(match_received.group(1))
                ping_dict['success']['probes_sent'] = probes_sent
                ping_dict['success'][
                    'packet_loss'] = probes_sent - probes_received
            except Exception:
                msg = "Unexpected output data:\n{}".format(output)
                raise ValueError(msg)

            match = re.search(r"min/avg/max = (\d+)/(\d+)/(\d+)", output, re.M)
            if match:
                ping_dict['success'].update({
                    'rtt_min': float(match.group(1)),
                    'rtt_avg': float(match.group(2)),
                    'rtt_max': float(match.group(3)),
                })

                results_array = []
                match = re.findall(r"Reply from.+time=(\d+)", output, re.M)
                for i in match:
                    results_array.append({
                        'ip_address': str(destination),
                        'rtt': float(i)
                    })
                ping_dict['success'].update({'results': results_array})
        return ping_dict

    def __get_snmp_information(self):
        snmp_information = {}
        # command = 'display snmp-agent sys-info'
        # output = self.device.send_command(command)

        snmp_information = {
            'contact': str(''),
            'location': str(''),
            'community': {},
            'chassis_id': str('')
        }
        return snmp_information

    def __get_lldp_neighbors_detail(self, interface=''):
        """
        Return a detailed view of the LLDP neighbors as a dictionary.

        Sample output:
        {
        'TenGigE0/0/0/8': [
            {
                'parent_interface': u'Bundle-Ether8',
                'remote_chassis_id': u'8c60.4f69.e96c',
                'remote_system_name': u'switch',
                'remote_port': u'Eth2/2/1',
                'remote_port_description': u'Ethernet2/2/1',
                'remote_system_description': u'''huawei os''',
                'remote_system_capab': u'B, R',
                'remote_system_enable_capab': u'B'
            }
        ]
        }
        """
        lldp_neighbors = {}
        return lldp_neighbors

    def __get_ntp_peers(self):
        """
        Return the NTP peers configuration as dictionary.

        Sample output:
        {
            '192.168.0.1': {},
            '17.72.148.53': {},
            '37.187.56.220': {},
            '162.158.20.18': {}
        }
        """
        ntp_server = {}
        # command = "display ntp session"
        # output = self.device.send_command(command)
        return ntp_server

    def __get_ntp_servers(self):
        """
        Return the NTP servers configuration as dictionary.

        Sample output:
        {
            '192.168.0.1': {},
            '17.72.148.53': {},
            '37.187.56.220': {},
            '162.158.20.18': {}
        }
        """
        ntp_server = {}
        # command = "display ntp trace"
        # output = self.device.send_command(command)
        return ntp_server

    def __get_ntp_stats(self):
        ntp_stats = []
        # command = "display ntp status"
        # output = self.device.send_command(command)
        return ntp_stats

    @staticmethod
    def _separate_section(separator, content):
        if content == "":
            return []

        # Break output into per-interface sections
        interface_lines = re.split(separator, content, flags=re.M)

        if len(interface_lines) == 1:
            msg = "Unexpected output data:\n{}".format(interface_lines)
            raise ValueError(msg)

        # Get rid of the blank data at the beginning
        interface_lines.pop(0)

        # Must be pairs of data (the separator and section corresponding to it)
        if len(interface_lines) % 2 != 0:
            msg = "Unexpected output data:\n{}".format(interface_lines)
            raise ValueError(msg)

        # Combine the separator and section into one string
        intf_iter = iter(interface_lines)

        try:
            new_interfaces = [line + next(intf_iter, '') for line in intf_iter]
        except TypeError:
            raise ValueError()
        return new_interfaces

    def _delete_file(self, filename):
        command = 'delete /unreserved /quiet {0}'.format(filename)
        self.device.send_command(command)

    def _save_config(self, filename=''):
        """Save the current running config to the given file."""
        command = 'save {}'.format(filename)
        save_log = self.device.send_command(command,
                                            max_loops=10,
                                            expect_string=r'Y/N')
        # Search pattern will not be detected when set a new hostname, so don't use auto_find_prompt=False
        save_log += self.device.send_command('y', expect_string=r'<.+>')
        search_result = re.search("successfully", save_log, re.M)
        if search_result is None:
            msg = "Failed to save config. Command output:{}".format(save_log)
            raise CommandErrorException(msg)

    def _load_config(self, config_file):
        command = 'rollback configuration to file {0}'.format(config_file)
        rollback_result = self.device.send_command(command,
                                                   expect_string=r'Y/N')
        rollback_result += self.device.send_command(
            'y', expect_string=r'[<\[].+[>\]]')
        search_result = re.search("clear the information", rollback_result,
                                  re.M)
        if search_result is not None:
            rollback_result += self.device.send_command('y',
                                                        expect_string=r'<.+>')

        search_result = re.search("succeeded|finished", rollback_result, re.M)
        if search_result is None:
            msg = "Failed to load config. Command output:{}".format(
                rollback_result)
            raise CommandErrorException(msg)

    def _replace_candidate(self, filename, config):
        if not filename:
            filename = self._create_tmp_file(config)
        else:
            if not os.path.isfile(filename):
                raise ReplaceConfigException(
                    "File {} not found".format(filename))

        self.replace_file = filename

        if not self._enough_space(self.replace_file):
            msg = 'Could not transfer file. Not enough space on device.'
            raise ReplaceConfigException(msg)

        need_transfer = True
        if self._check_file_exists(self.replace_file):
            if self._check_md5(self.replace_file):
                need_transfer = False
        if need_transfer:
            dest = os.path.basename(self.replace_file)
            # full_remote_path = 'flash:/{}'.format(dest)
            with paramiko.SSHClient() as ssh:
                ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
                ssh.connect(hostname=self.hostname,
                            username=self.username,
                            password=self.password,
                            port=self.port,
                            look_for_keys=False)

                try:
                    with paramiko.SFTPClient.from_transport(
                            ssh.get_transport()) as sftp_client:
                        sftp_client.put(self.replace_file, dest)
                    # with SCPClient(ssh.get_transport()) as scp_client:
                    #     scp_client.put(self.replace_file, dest)
                except Exception as e:
                    msg = 'Could not transfer file. There was an error during transfer:' + str(
                        e)
                    raise ReplaceConfigException(msg)
        self.config_replace = True
        if config and os.path.isfile(self.replace_file):
            os.remove(self.replace_file)

    def _verify_remote_file_exists(self, dst, file_system='flash:'):
        command = 'dir {0}/{1}'.format(file_system, dst)
        output = self.device.send_command(command)
        if 'No file found' in output:
            raise ReplaceConfigException('Could not transfer file.')

    def _check_file_exists(self, cfg_file):
        command = 'dir {}'.format(cfg_file)
        output = self.device.send_command(command)
        if 'No file found' in output:
            return False
        return True

    def _check_md5(self, dst):
        dst_hash = self._get_remote_md5(dst)
        src_hash = self._get_local_md5(dst)
        if src_hash == dst_hash:
            return True
        return False

    @staticmethod
    def _get_local_md5(dst, blocksize=2**20):
        md5 = hashlib.md5()
        local_file = open(dst, 'rb')
        buf = local_file.read(blocksize)
        while buf:
            md5.update(buf)
            buf = local_file.read(blocksize)
        local_file.close()
        return md5.hexdigest()

    def _get_remote_md5(self, dst):
        command = 'display system file-md5 {0}'.format(dst)
        output = self.device.send_command(command)
        filename = os.path.basename(dst)
        match = re.search(filename + r'\s+(?P<md5>\w+)', output, re.M)
        if match is None:
            msg = "Unexpected format: {}".format(output)
            raise ValueError(msg)
        return match.group('md5')

    def _commit_merge(self):
        commands = [
            command for command in self.merge_candidate.splitlines() if command
        ]
        output = ''

        try:
            output += self.device.send_command('system-view',
                                               expect_string=r'\[.+\]')
            for command in commands:
                output += self.device.send_command(command,
                                                   expect_string=r'\[.+\]')

            if self.device.check_config_mode():
                check_error = re.search("error", output, re.IGNORECASE)
                if check_error is not None:
                    return_log = self.device.send_command(
                        'return', expect_string=r'[<\[].+[>\]]')
                    if 'Uncommitted configurations' in return_log:
                        # Discard uncommitted configuration
                        return_log += self.device.send_command(
                            'n', expect_string=r'<.+>')
                    output += return_log
                    raise MergeConfigException('Error while applying config!')
                output += self.device.send_command('commit',
                                                   expect_string=r'\[.+\]')
                output += self.device.send_command('return',
                                                   expect_string=r'<.+>')
            else:
                raise MergeConfigException('Not in configuration mode.')
        except Exception as e:
            msg = str(e) + '\nconfiguration output: ' + output
            raise MergeConfigException(msg)

    def _get_merge_diff(self):
        diff = []
        running_config = self.get_config(retrieve='running')['running']
        running_lines = running_config.splitlines()
        for line in self.merge_candidate.splitlines():
            if line not in running_lines and line:
                if line[0].strip() != '!':
                    diff.append(line)
        return '\n'.join(diff)

    def _get_diff(self, filename=None):
        """Get a diff between running config and a proposed file."""
        if filename is None:
            return self.device.send_command('display configuration changes')
        return self.device.send_command(
            'display configuration changes running file ' + filename)

    def _enough_space(self, filename):
        flash_size = self._get_flash_size()
        file_size = os.path.getsize(filename)
        if file_size > flash_size:
            return False
        return True

    def _get_flash_size(self):
        command = 'dir {}'.format('flash:')
        output = self.device.send_command(command)

        match = re.search(r'\(\d.*KB free\)', output, re.M)
        if match is None:
            msg = "Failed to get free space of flash (not match). Log: {}".format(
                output)
            raise ValueError(msg)

        kbytes_free = 0
        num_list = map(int, re.findall(r'\d+', match.group()))
        for index, val in enumerate(reversed(num_list)):
            kbytes_free += val * (1000**index)
        bytes_free = kbytes_free * 1024
        return bytes_free

    @staticmethod
    def _parse_uptime(uptime_str):
        """Return the uptime in seconds as an integer."""
        (years, weeks, days, hours, minutes, seconds) = (0, 0, 0, 0, 0, 0)

        years_regx = re.search(r"(?P<year>\d+)\syear", uptime_str)
        if years_regx is not None:
            years = int(years_regx.group(1))
        weeks_regx = re.search(r"(?P<week>\d+)\sweek", uptime_str)
        if weeks_regx is not None:
            weeks = int(weeks_regx.group(1))
        days_regx = re.search(r"(?P<day>\d+)\sday", uptime_str)
        if days_regx is not None:
            days = int(days_regx.group(1))
        hours_regx = re.search(r"(?P<hour>\d+)\shour", uptime_str)
        if hours_regx is not None:
            hours = int(hours_regx.group(1))
        minutes_regx = re.search(r"(?P<minute>\d+)\sminute", uptime_str)
        if minutes_regx is not None:
            minutes = int(minutes_regx.group(1))
        seconds_regx = re.search(r"(?P<second>\d+)\ssecond", uptime_str)
        if seconds_regx is not None:
            seconds = int(seconds_regx.group(1))

        uptime_sec = (years * YEAR_SECONDS) + (weeks * WEEK_SECONDS) + (days * DAY_SECONDS) + \
                     (hours * 3600) + (minutes * 60) + seconds
        return uptime_sec

    @staticmethod
    def _create_tmp_file(config):
        tmp_dir = tempfile.gettempdir()
        rand_fname = str(uuid.uuid4())
        filename = os.path.join(tmp_dir, rand_fname)
        with open(filename, 'wt') as fobj:
            fobj.write(config)
        return filename
Ejemplo n.º 27
0
#     "secret": password,
#     "device_type": "cisco_ios",
#     "session_log": "my_output.txt",
# }
# Execute the following sequence of events using Netmiko:
# Execute the config_mode() method and print the new prompt using find_prompt()

from netmiko import ConnectHandler
from getpass import getpass
from datetime import datetime

password = getpass()
device = {
    "host": "cisco4.lasthop.io",
    "username": "******",
    "password": password,
    "secret": password,
    "device_type": "cisco_ios",
    "session_log": "my_output.txt",
}

net_connect = ConnectHandler(**device)
print("\nEnter Config mode")
net_connect.config_mode()
print("\n>>>>>>>")
print("Checking if it's in config mode")
print("Config mode check: {}".format(net_connect.check_config_mode()))
print("Current Prompt: {}".format(net_connect.find_prompt()))
print()

net_connect.disconnect()
    'device_type': 'juniper',
    'ip': '50.76.53.27',
    'username': '******',
    'password': '******',
    'port': 9822
}

rtr2 = ConnectHandler(**pynetrtr2)
# passes in dictionary key values into the function

output = rtr2.find_prompt()
print output

output = rtr2.send_command('show run | in logging')
print output

output = rtr2.config_mode()
print output

output = rtr2.check_config_mode()
print output

output = rtr2.send_command('logging buffered 32769')
print output

output = rtr2.send_command('end')
print output

output = rtr2.send_command('show run | in logging')
print output
Ejemplo n.º 29
0
 def run(self):
     if self.device['device_type'] == 'cisco_ios_serial':
         try:
             console = ConnectHandler(
                 **self.device
             )  # Connect to the Device to verify credentials.
             config_mode = console.check_config_mode()
             if config_mode is True:
                 console.exit_config_mode()
                 self.signal.emit('Router was in config mode try again.')
                 return
             console.enable()  # Enter Enable Mode
             show_ver = console.send_command('show run | inc version 1')
             self.signal.emit(show_ver)
             version = self.get_version_cisco(show_ver)
             if version >= 15.4:
                 pass
             else:
                 show_flash = console.send_command('dir flash: | i .bin')
                 self.signal.emit('----ERROR----\n'
                                  ' Old version of IOS Detected\n'
                                  ' Correct version may be in flash:')
                 self.signal.emit(show_flash)
                 self.signal.emit(
                     '\n>========== Reminder ==========<\n'
                     'Ensure the config you plan to load is compatible\n'
                     ' with the version of IOS you are using.\n '
                     'If not contact the help desk.\n'
                     '>========== Reminder ==========<\n')
             console.disconnect(
             )  # disconnect so it can be modified later on the LoadTab
             self.signal.emit(
                 'Credentials Verified on Console!')  # Congrats you made it
         except ValueError:  # most likely com port fault.
             self.signal.emit(
                 '...COM Port does not appear to be working. \nTry one of these:'
             )
             ports = list(serial.tools.list_ports.comports()
                          )  # You used the wrong one here let me help you.
             for p in ports:  # may just automate this in the future using this method if only one port is found
                 self.signal.emit(p[0])
             return
         except NetMikoAuthenticationException:  # Exactly what it says in the error.
             self.signal.emit(
                 "Check your username/password. Make sure you have an account on this device."
             )
             return
     elif self.device['device_type'] == 'cisco_ios_telnet':
         try:
             telnet = ConnectHandler(
                 **self.device
             )  # Connect to the Device to verify credentials.
             telnet.enable()  # Enter Enable Mode
             if telnet == True:
                 telnet.send_command('exit')
             show_ver = telnet.send_command('show run | inc version 1')
             self.signal.emit(show_ver)
             version = self.get_version_cisco(show_ver)
             if version >= 15.4:
                 pass
             else:
                 show_flash = telnet.send_command('dir flash: | i .bin')
                 self.signal.emit('----ERROR----\n'
                                  ' Old version of IOS Detected\n'
                                  ' Correct version may be in flash:')
                 self.signal.emit(show_flash)
                 self.signal.emit(
                     '\n>========== Reminder ==========<\n'
                     'Ensure the config you plan to load is compatible\n'
                     ' with the version of IOS you are using.\n '
                     'If not contact the help desk.\n'
                     '>========== Reminder ==========<\n')
             telnet.disconnect()
             self.signal.emit('Credentials Verified on Telnet!')
         except TimeoutError:  # Exactly what it says in the error.
             self.signal.emit(
                 "Telnet Error: Make sure the IP address is correct.")
             return
         except NetMikoAuthenticationException:  # Exactly what it says in the error.
             self.signal.emit(
                 "Check your username/password. Make sure you have an account on this device."
             )
             return
     elif self.device['device_type'] == 'cisco_ios':
         try:
             ssh = ConnectHandler(
                 **self.device
             )  # Connect to the Device to verify credentials.
             ssh.enable()  # Enter Enable Mode
             if ssh == True:
                 ssh.send_command('exit')
             show_ver = ssh.send_command('show run | inc version 1')
             self.signal.emit(show_ver)
             version = self.get_version_cisco(show_ver)
             if version >= 15.4:
                 pass
             else:
                 show_flash = ssh.send_command('dir flash: | i .bin')
                 self.signal.emit('----ERROR----\n'
                                  ' Old version of IOS Detected\n'
                                  ' Correct version may be in flash:')
                 self.signal.emit(show_flash)
                 self.signal.emit(
                     '\n>========== Reminder ==========<\n'
                     'Ensure the config you plan to load is compatible\n'
                     ' with the version of IOS you are using.\n '
                     'If not contact the help desk.\n'
                     '>========== Reminder ==========<\n')
             ssh.disconnect()
             self.signal.emit('Credentials Verified on SSH!')
         except NetMikoTimeoutException:  # Exactly what it says in the error.
             self.signal.emit(
                 "SSH Error: Make sure the IP address is correct.")
             return
         except NetMikoAuthenticationException:  # Exactly what it says in the error.
             self.signal.emit(
                 "Check your username/password. Make sure you have an account on this device."
             )
             return
     else:
         return
Ejemplo n.º 30
0
import pexpect
import time
import netmiko
from netmiko import ConnectHandler

password = '******'

pynet1 = {
    'device_type': 'cisco_ios',
    'ip': '50.76.53.27',
    'username': '******',
    'password': password,
}

pynet2 = {
    'device_type': 'cisco_ios',
    'ip': '50.76.53.27',
    'username': '******',
    'password': password,
    'port': 8022,
}

rc = ConnectHandler(**pynet2)
rc.config_mode()
output = rc.find_prompt()
print output
output = rc.check_config_mode()
print output


Ejemplo n.º 31
0
    'device_type': 'cisco_ios',
    'ip': '192.168.32.200',
     'username': '******',
    'password': '******',
        'port': 22,
        'secret': 'cisco123',  # no username admin pri 15  // # enable secret cisco123
        'verbose': True,
    }

# connection123 = object, ** = dictionary used to call function
connection123 = ConnectHandler(**cisco_device)

 prompt = connection123.find_prompt()
  print(prompt)
   if '>' in prompt:
        connection123.enable()
    # mode = connection123.check_enable_mode()
    # print(mode)
    output = connection123.send_command('show ip int br')
    print(output)

    mode = connection123.check_config_mode()
    # print(mode)
    if not mode:
        connection123.config_mode()
    # mode = connection123.check_config_mode()
    # print(mode)
    output = connection123.send_command('username joy password python123')
    output = connection123.send_command('do show run | i user')
    print(output)
Ejemplo n.º 32
0
def main():
    net_connect = ConnectHandler(**pynet.rtr1)
    print "Entering config mode..."
    print net_connect.config_mode()
    print "In config mode: " + str(net_connect.check_config_mode())
    print "Current Prompt: " + net_connect.find_prompt()
Ejemplo n.º 33
0
    'username': '******',
    'password': '******',  # optional, defaults to 22
    'secret': 'cpe',  # optional, defaults to ''
}

connection = ConnectHandler(**cisco_device)

# Enter enable() mode
connection.enable()

if connection.check_enable_mode():
    # Enter config mode
    connection.config_mode()

    # Check if in config mode
    if connection.check_config_mode():
        # config
        command = [
            "hostname C-SW-5", "int g1/0/24", "no sw",
            "ip address 172.58.10.6 255.255.255.252", "exit", "ip routing",
            "ip route 100.254.10.4 255.255.255.252 172.58.10.5",
            "ip route 100.254.10.0 255.255.255.252 172.58.10.5",
            "ip route 172.58.10.0 255.255.255.252 172.58.10.5"
        ]
        connection.send_config_set(config_commands=command)

    # Verify
    # Show hostname
    prompt = connection.find_prompt()
    print("#Verify hostname\n")
    print(prompt)
Ejemplo n.º 34
0
from netmiko import ConnectHandler

pynet1 = {
    'device_type': 'cisco_ios',
    'ip': '184.105.247.70',
    'username': '******',
    'password': '******',
}

pynet2 = {
    'device_type': 'cisco_ios',
    'ip': '184.105.247.71',
    'username': '******',
    'password': '******',
}

juniper_srx = {
    'device_type': 'juniper',
    'ip': '184.105.247.76',
    'username': '******',
    'password': '******',
    'secret': ''
}

sess1=ConnectHandler(**pynet2)
sess1.config_mode()
print "CONFIG MODE %s" %sess1.check_config_mode()
sess1.send_config_set(['logging buffer 10000'])

print sess1.send_command("sho run | i logging")
Ejemplo n.º 35
0
def ConfigurationTest(ip,
                      Device_Type_Num=0,
                      User_Pass_Num=0,
                      Passowrd_Enable_Num=0):
    # def ConfigurationTest(ip,Device_Type_Num= 0,User_Pass_Num= 0):

    if ConfigurationTest_Boolen == 1:
        return ConfigurationTest_Boolen == 1

# If increment of Num is out of range for User_Pass_Num and Device_Type_Num return 1
    elif User_Pass_Num >= len(Username_Device):
        print(f"Username Not in Range For IP\t{ip}\n")
        return ConfigurationTest_Boolen == 1
    elif Device_Type_Num >= len(Device_Type):
        print(f"Connection type Not in Range For IP\t{ip}\n")
        return ConfigurationTest_Boolen == 1
    elif Passowrd_Enable_Num >= len(Passowrd_Device_Enable):
        print(f"Enable Pass Not in Range For IP\t{ip}\n")
        return ConfigurationTest_Boolen == 1
# If increment of Num is in range for User_Pass_Num and Device_Type_Num contune
    else:

        iosv_l2 = {
            'device_type': str(Device_Type[Device_Type_Num]
                               ),  ##### Type of connection SSH/Telnet
            'ip': str(ip),
            'username': Username_Device[User_Pass_Num],
            'password': Passowrd_Device[User_Pass_Num],
            # 'global_delay_factor': 10,
            # 'secret':'cs'
            'secret': Passowrd_Device_Enable[Passowrd_Enable_Num],
            # 'timeout':5
            # 'session_timeout':5
        }

        try:
            # time.sleep(3)
            Conf_Variables = [
            ]  # To check if any faliure on the configuration after sending it
            net_connect = ConnectHandler(**iosv_l2)

            # print(net_connect.find_prompt())

            ############ function to check output to send any confirmation message as pass or confirmation of yes or no
            def SpecialConfirmation(command, message, reply):
                net_connect.config_mode()  #To enter config mode
                print("SpecialConfirmation Config")
                try:
                    if Device_Type[Device_Type_Num] == "cisco_ios_telnet":
                        print("First Write Telnet")
                        net_connect.remote_conn.write(str(command) + '\n')
                    else:
                        net_connect.remote_conn.sendall(str(command) + '\n')
                except:
                    print("Exception For Sendall ")
                print("SpecialConfirmation Before Sleep")
                time.sleep(3)
                print("SpecialConfirmation after Sleep")
                if Device_Type[Device_Type_Num] == "cisco_ios_telnet":
                    print("First READ Telnet")
                    output = net_connect.remote_conn.read_very_eager().decode(
                        "utf-8", "ignore")
                else:
                    output = net_connect.remote_conn.recv(65535).decode(
                        'utf-8')
                ReplyAppend = ''
                print("SpecialConfirmation output")
                print(output)
                try:
                    if str(message) in output:
                        for i in range(0, (len(reply))):
                            ReplyAppend += str(reply[i]) + '\n'
                        if Device_Type[Device_Type_Num] == "cisco_ios_telnet":
                            print("SECOND Telnet")
                            net_connect.remote_conn.write(ReplyAppend)
                            output = net_connect.remote_conn.read_very_eager(
                            ).decode("utf-8", "ignore")
                        else:
                            net_connect.remote_conn.sendall(ReplyAppend)
                            output = net_connect.remote_conn.recv(
                                65535).decode('utf-8')
                    print(output)
                except:
                    print("Confirmation Exception Error")
                return output

            print("Entered Device Successfully \t" + ip + "\n")

            ######################################################################
            ################ Here Is The Cisco Configuration  ####################
            ######################################################################
            print("check enable mode for " + str(ip))
            if not net_connect.check_enable_mode():
                net_connect.enable()
                print("entered enable mode for " + str(ip))

        ##################################################################
        ########### Check if in config mode or not to exit config mode
        ##################################################################
            if net_connect.check_config_mode():
                net_connect.exit_config_mode()
                print("After exiting config " + str(ip))
            print("After checking config " + str(ip))

            ######################################################################

            print("Terminal length \n")

            Configuration_Output = net_connect.send_command_timing(
                "termin len 0" + '\n\n')
            Configuration_Output = net_connect.send_command_timing(
                "show run " + '\n\n', strip_prompt=False, strip_command=False)
            Configuration_Output += net_connect.send_command_timing(
                "show ip inte br " + '\n\n',
                strip_prompt=False,
                strip_command=False)
            # Configuration_Switch=net_connect.send_command_timing("show fex  "+'\n\n' ,strip_prompt=False,strip_command=False)
            # Configuration_Output+=net_connect.send_command_timing("show cdp neighbors detail "+'\n\n' ,strip_prompt=False,strip_command=False)
            # Configuration_Switch+=net_connect.send_command_timing("show interfaces status  "+'\n\n' ,strip_prompt=False,strip_command=False)
            # Configuration_Output+=net_connect.send_command_timing("show inter desc "+'\n\n' ,strip_prompt=False,strip_command=False)
            # Configuration_Router=net_connect.send_command_timing("show ip ospf neighbor "+'\n\n' ,strip_prompt=False,strip_command=False)
            # Configuration_Output+=net_connect.send_command_timing("show version "+'\n\n' ,strip_prompt=False,strip_command=False)
            # Configuration_Output+=net_connect.send_command_timing("show cdp neighbors "+'\n\n' ,strip_prompt=False,strip_command=False)

            ################### for ARP ###############################################################
            ######################################################################

            # Configuration_Output_ID2=net_connect.send_command_timing("show ip arp vrf ID2 "+'\n\n'  ,strip_prompt=False,strip_command=False)
            # Configuration_Output_ID254=net_connect.send_command_timing("show ip arp vrf ID254 "+'\n\n'  ,strip_prompt=False,strip_command=False)
            ######################################################################

            # Configuration_Output=net_connect.send_command_timing("termin len 0"+'\n\n',delay_factor=5)
            # Configuration_Output=net_connect.send_command_timing("show run "+'\n\n' ,delay_factor=5,strip_prompt=False,strip_command=False)
            # Configuration_Output+=net_connect.send_command_timing("show ip inte br "+'\n\n',delay_factor=5,strip_prompt=False,strip_command=False)
            # Configuration_Switch=net_connect.send_command_timing("show fex  "+'\n\n',delay_factor=5,strip_prompt=False,strip_command=False)
            # Configuration_Output+=net_connect.send_command_timing("show cdp neighbors detail "+'\n\n',delay_factor=5,strip_prompt=False,strip_command=False)
            # Configuration_Switch+=net_connect.send_command_timing("show interfaces status  "+'\n\n',delay_factor=5,strip_prompt=False,strip_command=False)
            # Configuration_Output+=net_connect.send_command_timing("show inter desc "+'\n\n',delay_factor=5,strip_prompt=False,strip_command=False)
            # Configuration_Router=net_connect.send_command_timing("show ip ospf neighbor "+'\n\n',delay_factor=5,strip_prompt=False,strip_command=False)
            # Configuration_Output+=net_connect.send_command_timing("show version "+'\n\n',delay_factor=5,strip_prompt=False,strip_command=False)
            # Configuration_Output+=net_connect.send_command_timing("show cdp neighbors "+'\n\n',delay_factor=5,strip_prompt=False,strip_command=False)

            # Hostname_Output=net_connect.send_command("show run | i hostname"+'\n\n')

            # Configuration_Output+=net_connect.send_command_timing("show ip inte br "+'\n\n',strip_prompt=False,strip_command=False)

            print(f"This is after getting SHOW for IP\t{ip}")

            Hostname_Output = net_connect.send_command(
                "show run | i hostname" + '\n\n', delay_factor=5)

            ###########################################################################################################
            ##################    	Add new IPs from CDP Command     ##################################################
            ###########################################################################################################
            CDP_ALL = net_connect.send_command_timing(
                "show cdp neighbors detail | i IP address: " + '\n\n')
            # print("CDP_ALL\n")
            # print(CDP_ALL)
            # print(type(CDP_ALL))
            # change output to list of lines
            CDP_Lines_List = CDP_ALL.splitlines(
            )  # change output to list of lines
            CDP_IPs_List = []
            # change list of line to list of IPs wihtout IP address sentence
            for i in CDP_Lines_List:
                j = i.lstrip("IP address: ")
                CDP_IPs_List.append(j)
            # print("CDP_IPs_List for "+str(ip))
            # print(CDP_IPs_List)

            # check on each ip if it's in the mangement range or not and append it to new list if it's not exsit in the IPs list
            for i in CDP_IPs_List:
                if "192" in i:
                    # check on the IP to add it to the list
                    if i not in num:
                        num_New.append(i)
                        # num.append(i)
                    # CDP_IPs_List.remove(i)

        ###########################################################################################################
        ###########################################################################################################

        # if ip =="192.168.233.13":
        #       print (str (SpecialConfirmation("crypto key generate rsa general-keys" ,"modulus" ,"1024")))

            if net_connect.check_config_mode():
                net_connect.exit_config_mode()
            print("After second check config " + str(ip))

            # for k in TestPingIPs :
            # 		ping_result=net_connect.send_command_timing("ping "+k)
            # 		print (str(k)+" is "+str(ping_is_successful(ping_result))+" from "+str(ip))

            ################################################################################
            ####################### Test Ping For Rang Of IP  ##############################
            ################################################################################
            # for IpPing in TestPingIPs :
            #       PingPool="ping "+IpPing
            #       TestPingResult=net_connect.send_command_timing(PingPool+'\n\n')
            #       if ping_is_successful(TestPingResult) :
            #               TruePing.append(IpPing)
            #       else :
            #               FalsePing.append(IpPing)

            Spilt_Hostname_Ouput = Hostname_Output.split()
            Hostname_Output = ip + ".__" + Spilt_Hostname_Ouput[-1]
            # print ("After Split")

            ############### Append Configuration Variables to Global Variable ##########

            Conf_Variables.append(Hostname_Output)
            Conf_Variables.append(Configuration_Output)
            ############### Search in Configuration if any command error and return its IP ################
            for y in Conf_Variables:
                if "% Invalid input detected at '^' marker." in y:
                    FailedIps.append(ip + "   Invalid input")
#########################################################################################################
# Configuration_Output+=Configuration_Switch
# Configuration_Output+=Configuration_Router
            Hostname_Output_list.append(Hostname_Output)
            test = Configuration_Switch
            test += Configuration_Output
            test += Configuration_Router
            Configuration_Output_list.append(test)

            Configuration_Output_ID2_list.append(Configuration_Output_ID2)
            Configuration_Output_ID254_list.append(Configuration_Output_ID254)

            ############### SAVE Output IN FILES  #######################
            Global_Output.append(Hostname_Output)
            net_connect.disconnect()


################### Exception ###################################
        except socket_error as socket_err:
            ################ Print error from msg from the main Lib
            print(f"Socket Error: \n{socket_err}\t for IP {ip}\n")
            print("Continue")
            if '111' in f"Type {socket_err}":
                Device_Type_Num += 1
                if Device_Type_Num >= len(Device_Type):
                    FailedIps.append(ip + "   Socket or connection type Error")
                return ConfigurationTest(ip, Device_Type_Num, User_Pass_Num,
                                         Passowrd_Enable_Num)
            if '113' in f"Type {socket_err}":
                FailedIps.append(ip + "   No route to the host")
                return ConfigurationTest_Boolen == 1
            return ConfigurationTest_Boolen == 1

        except paramiko.ssh_exception.BadHostKeyException as badHostKeyException:
            ################ Print error from msg from the main Lib
            print(
                f"Unable to verify server's host key: \n{badHostKeyException}\n"
            )

        except paramiko.ssh_exception.NoValidConnectionsError as noValidConnectionsError:
            ################ Print error from msg from the main Lib
            print(f"no Valid Connections Error: \n{noValidConnectionsError}\n")

        except (NetMikoAuthenticationException
                ) as netmikoAuthenticationException:
            # print ('Authentication Failure\t' + ip)
            print(
                str(User_Pass_Num) + "   " +
                str(Username_Device[User_Pass_Num]) +
                " failed Authentication\t" + ip)
            ################ Print error from msg from the main Lib
            print(
                f"netmikoAuthenticationException : {netmikoAuthenticationException}\n"
            )
            User_Pass_Num += 1
            # If it tried all users and pass and failed add it to failedIps
            if User_Pass_Num >= len(Username_Device):
                FailedIps.append(ip + "   Authentication Error ")
            # if User_Pass_Num < len(Username_Device) :
            #       print("this is Authentication  "+str(ip)+" Device_Type "+str(Device_Type[Device_Type_Num])+" Username_Device " +str(Username_Device[User_Pass_Num])+" Passowrd_Device " +str(Passowrd_Device[User_Pass_Num]))
        # Recursive function
            return ConfigurationTest(ip, Device_Type_Num, User_Pass_Num,
                                     Passowrd_Enable_Num)
        except (NetMikoTimeoutException) as netmikoTimeoutException:
            # print ('Timeout  Failure\t' + ip)
            print(str(Device_Type_Num) + "\tTimeoutException\t" + ip)
            ################ Print error from msg from the main Lib
            print(f"netmikoTimeoutException : \n{netmikoTimeoutException}\n")
            Device_Type_Num += 1
            if Device_Type_Num >= len(Device_Type):
                FailedIps.append(ip + "   Timeout Error")
            # if  Device_Type_Num < len(Device_Type) :
            #       print("this is Timeout "+str(ip)+" Device_Type "+str(Device_Type[Device_Type_Num])+" Username_Device " +str(Username_Device[User_Pass_Num])+" Passowrd_Device " +str(Passowrd_Device[User_Pass_Num]))
            return ConfigurationTest(ip, Device_Type_Num, User_Pass_Num,
                                     Passowrd_Enable_Num)

        except (paramiko.ssh_exception.SSHException) as sshException:
            # print ('SSH  Failure\t' + ip)
            print(str(Device_Type_Num) + "\tSSHException\t" + ip + "\n")
            ################ Print error from msg from the main Lib
            print(
                f"Unable to establish SSH connection: \n{sshException}\t for IP {ip}\n"
            )
            Device_Type_Num += 1
            if Device_Type_Num >= len(Device_Type):
                FailedIps.append(ip + "   SSHException Error ")
            # if  Device_Type_Num < len(Device_Type) :
            #       print("this is SSHException "+str(ip)+" Device_Type "+str(Device_Type[Device_Type_Num])+" Username_Device " +str(Username_Device[User_Pass_Num])+" Passowrd_Device " +str(Passowrd_Device[User_Pass_Num]))
            return ConfigurationTest(ip, Device_Type_Num, User_Pass_Num,
                                     Passowrd_Enable_Num)

        except (ValueError):
            print(
                str(Passowrd_Enable_Num) + "   " +
                str(Passowrd_Device_Enable[Passowrd_Enable_Num]) +
                " Failed Enable Authentication\t" + ip)
            Passowrd_Enable_Num += 1
            if Passowrd_Enable_Num >= len(Passowrd_Device_Enable):
                FailedIps.append(ip + "   Enable Authentication Error ")
            return ConfigurationTest(ip, Device_Type_Num, User_Pass_Num,
                                     Passowrd_Enable_Num)

        except (EOFError) as eof_Error:
            ################ Print error from msg from the main Lib
            print(f"eof_Error : \n{eof_Error}\n")
            # print ('End of File wihle attempting device\t' +ip)
            FailedIps.append(ip + "   EOFError")
            # print("this is EOFError "+str(ip)+" Device_Type "+str(Device_Type[Device_Type_Num])+" Username_Device " +str(Username_Device[User_Pass_Num])+" Passowrd_Device " +str(Passowrd_Device[User_Pass_Num]))
            return ConfigurationTest_Boolen == 1

    ####################################################################
    ########## if you want to show error , comment next lines if you want to show which Ips have error remove comment  ##############
    ####################################################################
        except Exception as e:
            # print ('End of File wihle attempting device\t' +ip)
            FailedIps.append(ip + "   Exception as e")
            # print("this is EOFError "+str(ip)+" Device_Type "+str(Device_Type[Device_Type_Num])+" Username_Device " +str(Username_Device[User_Pass_Num])+" Passowrd_Device " +str(Passowrd_Device[User_Pass_Num]))
            return ConfigurationTest_Boolen == 1

    ####################################################################

    return ConfigurationTest_Boolen == 1
Ejemplo n.º 36
0
from getpass import getpass
import time

Pass = getpass()


Pynet2 = {
    'device_type': 'cisco_ios',
    'ip': '184.105.247.71',
    'username': '******',
    'password': Pass,
    'port': 22,
}


Pynet2Connect = ConnectHandler(**Pynet2)

print "Logging in..."
time.sleep(1)
Pynet2Prompt = Pynet2Connect.find_prompt()
print "\n", Pynet2Prompt, "\n\n"

print "Entering configuration mode..."
time.sleep(2)
Pynet2Config = Pynet2Connect.config_mode()
print "\n", Pynet2Config, "\n\n"

print "Checking if the router is in configuration mode..."
time.sleep(1)
print Pynet2Connect.check_config_mode()
Ejemplo n.º 37
0
# Use Netmiko to enter into configuration mode on pynet-rtr2. Also use Netmiko to verify your state (i.e. that you are currently in configuration mode).
from netmiko import ConnectHandler
from getpass import getpass
rtr2 = { 'device_type':'cisco_ios','ip':'184.105.247.71','username':'******',
'password':'******'}
pynet_rtr2 = ConnectHandler(**rtr2)
pynet_rtr2.config_mode()
print ('Are we in config mode for pynet_rtr2?')
print (pynet_rtr2.check_config_mode())

Ejemplo n.º 38
0
password = getpass()

pynet2 = {
            'device_type': 'cisco_ios',
            'ip': '50.76.53.27',
            'username': '******',
            'password': password,
            'port': 8022,
        }
# Connect to Cisco Router 2
pynet_rtr2 = ConnectHandler(**pynet2)

# Enter Config mode
pynet_rtr2.config_mode()

if (pynet_rtr2.check_config_mode()):
    outp = pynet_rtr2.send_command('logging buffered 25000')
   
    # Exit Config mode 
    pynet_rtr2.exit_config_mode()    

    # Obtain the running Config
    outp = pynet_rtr2.send_command('show runn | inc logging buffered 25000')

    if re.search(r'logging buffered 25000', outp):
        print "Config changed successfully!"
    else:
        print "Config changed unsuccessfully!"
else:
    print "Failed to enter Config mode!"
    
Ejemplo n.º 39
0


rtr1_conn = ConnectHandler(**rtr1)
rtr2_conn = ConnectHandler(**rtr2)
juniper_srx_conn = ConnectHandler(**juniper_srx)

print rtr1_conn.find_prompt()
print rtr2_conn.find_prompt()
print juniper_srx_conn.find_prompt()


rtr2_conn.config_mode()

print "On rtr1 are we in config mode?"
print rtr1_conn.check_config_mode()
print "On rtr2 are we in config mode?"
print rtr2_conn.check_config_mode()
print "On juniper_srx are we in config mode?"
print juniper_srx_conn.check_config_mode()

rtr2_conn.exit_config_mode()



show_commands = ['show arp']

output = rtr1_conn.send_command(show_commands[0])
print output

output = rtr2_conn.send_command(show_commands[0])
Ejemplo n.º 40
0
routers = [router1, router2, router3]

for router in routers:
    #VMs are running a little hot, give them some time.
    time.sleep(5)
    #Print the dictionary used to establish the connection
    print(router)
    rtr = ConnectHandler(**router)
    #Print the established connection
    print(rtr)
    #Enter enable mode if one exists
    rtr.enable()

    #Send the command show version and print the output
    output = rtr.send_command('show version')
    print(output)

    #Send the command show version and print the output
    output = rtr.send_command('show arp')
    print(output)

    #show the current prompt
    print(rtr.find_prompt())
    #Enter config mode
    rtr.config_mode()
    #show the current prompt
    print(rtr.find_prompt())
    #Check if or if not in config mode
    print(rtr.check_config_mode())
Ejemplo n.º 41
0
    'cisco_ios',  #device type from https://github.com/ktbyers/netmiko/blob/master/netmiko/ssh_dispatcher.py
    'host': '10.0.0.1',
    'username': '******',
    'password': '******',
    'port': 22,  # optional, default 22
    'secret': 'cisco',  # this is the enable password
    'verbose': True  # optional, default False
}

# connecting to the device and returning an ssh connection object
connection = ConnectHandler(**cisco_device)

# sending a command and getting the output

#prompt = connection.find_prompt()
#if '>' in prompt:
#   connection.enable()
output = connection.send_command('sh run')
print(output)
if not connection.check_config_mode():
    connection.config_mode()

#print(connection.check_config_mode())
#connection.send_command('username u1 secret cisco')

connection.exit_config_mode()
print(connection.check_config_mode())

# closing the connection
print('Closing connection')
connection.disconnect()
Ejemplo n.º 42
0
pynet_rtr2 = ConnectHandler(**pynet2)

#Print the prompts from both routers
prompt1 = pynet_rtr1.find_prompt()
prompt2 = pynet_rtr2.find_prompt()
print prompt1
print prompt2

#Get into config mode
response1 = pynet_rtr1.config_mode()
response2 = pynet_rtr2.config_mode()
print response1
print response2

#Double check config mode
response1 = pynet_rtr1.check_config_mode()
response2 = pynet_rtr2.check_config_mode()
print response1
print response2

#Exit config mode
response1 = pynet_rtr1.exit_config_mode()
response2 = pynet_rtr2.exit_config_mode()
print response1
print response2

#Send the command 'show ip int br' and print the output
response1 = pynet_rtr1.send_command('show ip int brief')
response2 = pynet_rtr2.send_command('show ip int brief')
print response1
print response2
Ejemplo n.º 43
0
class NetmikoSSH(object):
    """Contains methods for managing and using SSH connections for Network Devices using Netmiko"""

    __MAX_RECV_BUF = 10 * 1024 * 1024
    __existing_connections = {}

    def __init__(self):
        self._session = None
        self._node = None
        self._device = {}

    @staticmethod
    def _node_hash(node, port):
        """Get IP address and port hash from node dictionary.

        :param node: Node in topology.
        :param port: 
        :type node: dict
        :return: IP address and port for the specified node.
        :rtype: int
        """

        return hash(frozenset([node['mgmt_ip'], port]))

    @staticmethod
    def _get_device_type(node):
        device_os = node['os']
        if str(device_os) in os_netmiko_map.keys():
            return os_netmiko_map[str(device_os)]
        return None

    def net_connect(self, node):
        """Connect to node using Netmiko's inbuilt libraries.
        :param node: The node to disconnect from.
        :type node: dict
        """
        self._node = node
        ssh_port = Topology.get_ssh_port_from_node(node)

        node_hash = NetmikoSSH._node_hash(node, ssh_port)
        if node_hash in NetmikoSSH.__existing_connections:
            self._session = NetmikoSSH.__existing_connections[node_hash]
            logger.debug('reusing ssh: {0}'.format(self._session))
        else:
            start = time()
            self._device = {
                'device_type': NetmikoSSH._get_device_type(node),
                'ip': node['mgmt_ip'],
                'username': node['username'],
                'password': node['password'],
                'port': ssh_port
            }

            self._session = ConnectHandler(**self._device)
            NetmikoSSH.__existing_connections[node_hash] = self._session

            logger.trace('connect took {} seconds'.format(time() - start))
            logger.debug('new connection: {0}'.format(self._session))

        logger.debug('Connections: {0}'.format(
            str(NetmikoSSH.__existing_connections)))

    def net_disconnect(self, node):
        """Close SSH connection to the node.

        :param node: The node to disconnect from.
        :type node: dict
        """
        ssh_port = Topology.get_ssh_port_from_node(node)

        node_hash = NetmikoSSH._node_hash(node, ssh_port)

        if node_hash in NetmikoSSH.__existing_connections:
            logger.debug('Disconnecting peer: {}, {}'.format(
                node['name'], ssh_port))
            ssh = NetmikoSSH.__existing_connections.pop(node_hash)

        self._session.disconnect()

    def _reconnect(self):
        """Close the SSH connection and open it again."""

        node = self._node
        self.net_disconnect(node)
        self.net_connect(node)

    def config_mode(self):
        """Enter into config mode """
        self.net_connect(self._node)
        self._session.config_mode()

    def check_config_mode(self):
        """ Check if session is currently in config mode"""
        self.net_connect(self._node)
        return self._session.check_config_mode()

    def exit_config_mode(self):
        """Exit config mode"""
        self.net_connect(self._node)
        self._session.exit_config_mode()

    def clear_buffer(self):
        """ Clear logging buffer """
        self.net_connect(self._node)
        self._session.clear_buffer()

    def enable(self):
        """ Enter Enable Mode"""
        self.net_connect(self._node)
        self._session.enable()

    def exit_enable_mode(self):
        """ Exit enable mode """
        self.net_connect(self._node)
        self._session.exit_enable_mode()

    def find_prompt(self):
        """Return the current router prompt"""
        self.net_connect(self._node)
        self._session.find_prompt()

    def send_command(self, cmd):
        """Send command down the SSH channel and return output back
        :param cmd
        :type cmd: str
        """
        if cmd is None:
            raise TypeError('Command parameter is None')
        if len(cmd) == 0:
            raise ValueError('Empty command parameter')

        self.net_connect(self._node)
        return self._session.send_command(cmd)

    def send_config_set(self, config_cmds):
        """Send a set of configuration commands to remote device
        :param config_cmds
        :type config_cmds: str
        """
        if config_cmds is None:
            raise TypeError('Config Cmds parameter is None')
        self.net_connect(self._node)
        print "Netmiko NODE !!!\n\n"
        print self._node
        return self._session.send_config_set(config_cmds)

    def send_config_from_file(self, cfg_file):
        """Send a set of configuration commands loaded from a file
        :param cfg_file
        :type cfg_file: file
        """
        if not os.path.isfile(cfg_file):
            raise TypeError('Config file does not exist')
        self.net_connect(self._node)
        self._session.send_config_from_file(cfg_file)
Ejemplo n.º 44
0
def main():

    try: 
        hostname = raw_input("Enter remote host to test: ")
        username = raw_input("Enter remote username: "******"Enter remote host to test: ")
        username = input("Enter remote username: "******"***** Testing enable mode *****")
    net_connect.enable()
    if net_connect.check_enable_mode():
        print("Success: in enable mode")
    else:
        print("Fail...")
    print(net_connect.find_prompt())

    net_connect.exit_enable_mode()
    print("Out of enable mode")
    print(net_connect.find_prompt())

    # Test config mode 
    print()
    print("***** Testing config mode *****")
    net_connect.config_mode()
    if net_connect.check_config_mode():
        print("Success: in config mode")
    else:
        print("Fail...")
    print(net_connect.find_prompt())

    net_connect.exit_config_mode()
    print("Out of config mode")
    print(net_connect.find_prompt())

    # Test config mode (when already at root prompt)
    print()
    print("***** Testing config mode when already root *****")
    net_connect.enable()
    if net_connect.check_enable_mode():
        print("Success: in enable mode")
    else:
        print("Fail...")
    print(net_connect.find_prompt())
    print("Test config_mode while already at root prompt")
    net_connect.config_mode()
    if net_connect.check_config_mode():
        print("Success: still at root prompt")
    else:
        print("Fail...")
    net_connect.exit_config_mode()
    # Should do nothing
    net_connect.exit_enable_mode()
    print("Out of config/enable mode")
    print(net_connect.find_prompt())

    # Send config commands
    print()
    print("***** Testing send_config_set *****")
    print(net_connect.find_prompt())
    output = net_connect.send_config_set(['ls -al'])
    print(output)
    print()
Ejemplo n.º 45
0
#!/usr/bin/env python

from netmiko import ConnectHandler

rtr2 = {
    'device_type': 'cisco_ios',
    'ip': '184.105.247.71',
    'username': '******',
    'secret': '',
    'port': '22',
    'password': '******'
    }

conn1 = ConnectHandler(**rtr2)
conn1.config_mode()

if conn1.check_config_mode():
    print "here you are in config mode"
    print "your prompt is :",
    print conn1.find_prompt()
else:
    print "you are not in config mode"
    print "your prompt is :",
    print conn1.find_prompt()
Ejemplo n.º 46
0
    'device_type':
    'cisco_ios',  #device type from https://github.com/ktbyers/netmiko/blob/master/netmiko/ssh_dispatcher.py
    'host': '10.1.1.10',
    'username': '******',
    'password': '******',
    'port': 22,  # optional, default 22
    'secret': 'cisco',  # this is the enable password
    'verbose': True  # optional, default False
}
connection = ConnectHandler(**cisco_device)

# getting the router's prompt
prompt = connection.find_prompt()
if '>' in prompt:
    connection.enable()  # entering the enable mode

output = connection.send_command('sh run')
print(output)

if not connection.check_config_mode(
):  # returns True if it's already in the global config mode
    connection.config_mode()  # entering the global config mode

# print(connection.check_config_mode())
connection.send_command('username u3 secret cisco')

connection.exit_config_mode()  # exiting the global config mode
print(connection.check_config_mode())

print('Closing connection')
connection.disconnect()
Ejemplo n.º 47
0
    'password': password,
}

net_connect1 = ConnectHandler(**pynet_rtr1)

output = net_connect1.send_command('show ip int brief')
print output

device_list = [pynet_rtr1, pynet_rtr2, pynet_jnpr_srx1]

for i in device_list:
    net_connect2 = ConnectHandler(**i)
    output = net_connect2.send_command('show arp')
    print output

net_connect3 = ConnectHandler(**pynet_rtr2)
net_connect3.config_mode()

if net_connect3.check_config_mode() == True:
    print 'You are in configuration mode for {}'.format('pynet_rtr2')
    net_connect3.send_command('logging buffered 19999')
    net_connect3.exit_config_mode()

outp = net_connect3.send_command('show run | sec logging')
print outp

net_connect3.send_config_from_file(config_file='config_commands.txt')

outp = net_connect3.send_command('show run | sec log')
print outp
Ejemplo n.º 48
0
connection = ConnectHandler(**router1)
#output = connection.send_command('show ip int brief')
#print(output)
prompt = connection.find_prompt()
print(prompt)
if '>' in prompt:
    connection.enable()

output1 = connection.send_command('show run | in hostname')
print(output1)
connection.disconnect()

connection1 = ConnectHandler(**router2)
prompt1 = connection1.find_prompt()
print(prompt1)
if '>' in prompt1:
    connection1.enable()

output2 = connection1.send_command('show run | in username')
print(output2)

mode = connection1.check_config_mode()
print(mode)
if not mode:
    connection1.config_mode()

mode = connection1.check_config_mode()
print(mode)
#output = connection1.send_command('username test1 password test123\n')
connection.disconnect()
Ejemplo n.º 49
0
conn = ConnectHandler(
    **cisco_device
)  #** this is a kwargs style of calling functions, it unpacks a DICTIONARY into the FUNCTION ARGUMENTs
print("  *** Connecting to a device ***  ")
### PROMPT -  we can find it in which prompt we are
prompt = conn.find_prompt()
print(prompt)
# calling the enable method of the CONN OBJECT
conn.enable(
)  # need to pass enable secret : ValueError: Failed to enter enable mode. Please ensure you pass the 'secret' argument to ConnectHandler.

prompt = conn.find_prompt()
print(prompt)
## Sending command to the device :
#variable_output = conn.send_command('show run')
#print(variable_output)
'''Global configuration mode'''
print(
    conn.check_config_mode()
)  ###Checking if we are already in global conf mode, it returns FALSE it means we are not in global mode
conf_mode = conn.config_mode(
)  ###entering global configuration mode, we call config mode method of CONN object
print(conf_mode)
'''we can use also 
if not conn.check_config_mode()
       conn.config_mode() '''

#Closing connection
print(' *** Connection is diconnected *** ')
conn.disconnect()
Ejemplo n.º 50
0
    'username': '******',
    'password': password,
    'port': 8022,
}

juniper_srx = {
    'device_type': 'juniper',
    'ip': '50.76.53.27',
    'username': '******',
    'password': password,
    'secret': '',
    'port': 9822,
}

#rtr1=ConnectHandler(**pynet1)
rtr2 = ConnectHandler(**pynet2)
#srx=ConnectHandler(**juniper_srx)

rtr2.find_prompt()
rtr2.config_mode()
if rtr2.check_config_mode():
    print 'Pynet-rtr2 is indeed in configuration mode\n'
else:
    print 'Pynet-rtr2 is in global configuration mode \n'
#print rtr1.send_command('show ip int brief')
#print rtr1.send_command('show run | inc logging buffered')
#config_set=['logging buffered 65000']
#print rtr1.send_config_set(config_set)
#print rtr1.send_command('show run | inc logging buffered')
#print dir(rtr1)
Ejemplo n.º 51
0
def ConfigurationTest(ip,
                      Device_Type_Num=0,
                      User_Pass_Num=0,
                      Passowrd_Enable_Num=0):
    global num_New  # so we can edit it in this Function
    # def ConfigurationTest(ip,Device_Type_Num= 0,User_Pass_Num= 0):

    if ConfigurationTest_Boolen == 1:
        return ConfigurationTest_Boolen == 1

# If increment of Num is out of range for User_Pass_Num and Device_Type_Num return 1
    elif User_Pass_Num >= len(Username_Device):
        print(f"Username Not in Range For IP\t{ip}\n")
        return ConfigurationTest_Boolen == 1
    elif Device_Type_Num >= len(Device_Type):
        print(f"Connection type Not in Range For IP\t{ip}\n")
        return ConfigurationTest_Boolen == 1
    elif Passowrd_Enable_Num >= len(Passowrd_Device_Enable):
        print(f"Enable Pass Not in Range For IP\t{ip}\n")
        return ConfigurationTest_Boolen == 1

# If increment of Num is in range for User_Pass_Num and Device_Type_Num contune
    else:

        iosv_l2 = {
            'device_type': str(Device_Type[Device_Type_Num]
                               ),  ##### Type of connection SSH/Telnet
            'ip': str(ip),
            'username': Username_Device[User_Pass_Num],
            'password': Passowrd_Device[User_Pass_Num],
            'global_delay_factor':
            15,  #  if there is authentication problem allow this
            # 'secret':'cs'
            'secret': Passowrd_Device_Enable[Passowrd_Enable_Num],
            # 'timeout':10
            'session_timeout':
            10  #  if there is authentication problem allow this
        }

        try:
            # time.sleep(3)
            Conf_Variables = [
            ]  # To check if any faliure on the configuration after sending it
            net_connect = ConnectHandler(**iosv_l2)

            # print(net_connect.find_prompt())

            ############ function to check output to send any confirmation message as pass or confirmation of yes or no
            def SpecialConfirmation(command, message, reply):
                net_connect.config_mode()  #To enter config mode
                print("SpecialConfirmation Config")
                try:
                    if Device_Type[Device_Type_Num] == "cisco_ios_telnet":
                        print("First Write Telnet")
                        net_connect.remote_conn.write(str(command) + '\n')
                    else:
                        net_connect.remote_conn.sendall(str(command) + '\n')
                except:
                    print("Exception For Sendall ")
                print("SpecialConfirmation Before Sleep")
                time.sleep(3)
                print("SpecialConfirmation after Sleep")
                if Device_Type[Device_Type_Num] == "cisco_ios_telnet":
                    print("First READ Telnet")
                    output = net_connect.remote_conn.read_very_eager().decode(
                        "utf-8", "ignore")
                else:
                    output = net_connect.remote_conn.recv(65535).decode(
                        'utf-8')
                ReplyAppend = ''
                print("SpecialConfirmation output")
                print(output)
                try:
                    if str(message) in output:
                        for i in range(0, (len(reply))):
                            ReplyAppend += str(reply[i]) + '\n'
                        if Device_Type[Device_Type_Num] == "cisco_ios_telnet":
                            print("SECOND Telnet")
                            net_connect.remote_conn.write(ReplyAppend)
                            output = net_connect.remote_conn.read_very_eager(
                            ).decode("utf-8", "ignore")
                        else:
                            net_connect.remote_conn.sendall(ReplyAppend)
                            output = net_connect.remote_conn.recv(
                                65535).decode('utf-8')
                    print(output)
                except:
                    print("Confirmation Exception Error")
                return output

            print("Entered Device Successfully \t" + ip + "\n")

            ######################################################################
            ################ Here Is The Cisco Configuration  ####################
            ######################################################################
            print("check enable mode for " + str(ip))
            if not net_connect.check_enable_mode():
                net_connect.enable()
                print("entered enable mode for " + str(ip))

        ##################################################################
        ########### Check if in config mode or not to exit config mode
        ##################################################################
            if net_connect.check_config_mode():
                net_connect.exit_config_mode()
                print("After exiting config to perform show commands " +
                      str(ip))
            print("After checking config to perform show commands " + str(ip))

            ######################################################################

            print("Terminal length \n")
            ## Try this First
            Configuration_Output = ""
            Configuration_Output = net_connect.send_command_timing(
                "termin len 0" + '\n\n')
            # Configuration_Output=net_connect.send_command_timing("show run "+'\n\n'  ,strip_prompt=False,strip_command=False)
            # Configuration_Output+=net_connect.send_command_timing("show ip inte br "+'\n\n' ,strip_prompt=False,strip_command=False)
            # Configuration_Switch=net_connect.send_command_timing("show fex  "+'\n\n' ,strip_prompt=False,strip_command=False)
            # Configuration_Output+=net_connect.send_command_timing("show cdp neighbors detail "+'\n\n' ,strip_prompt=False,strip_command=False)
            # Configuration_Switch+=net_connect.send_command_timing("show interfaces status  "+'\n\n' ,strip_prompt=False,strip_command=False)
            # Configuration_Output+=net_connect.send_command_timing("show inter desc "+'\n\n' ,strip_prompt=False,strip_command=False)
            # Configuration_Router=net_connect.send_command_timing("show ip ospf neighbor "+'\n\n' ,strip_prompt=False,strip_command=False)
            # Configuration_Output+=net_connect.send_command_timing("show version "+'\n\n' ,strip_prompt=False,strip_command=False)
            # Configuration_Output+=net_connect.send_command_timing("show cdp neighbors "+'\n\n' ,strip_prompt=False,strip_command=False)
            ################### for ARP ###############################################################
            ######################################################################

            # Configuration_Output_ID2=net_connect.send_command_timing("show ip arp vrf ID2 "+'\n\n'  ,strip_prompt=False,strip_command=False)
            # Configuration_Output_ID254=net_connect.send_command_timing("show ip arp vrf ID254 "+'\n\n'  ,strip_prompt=False,strip_command=False)
            ######################################################################

            # Configuration_Output=net_connect.send_command_timing("termin len 0"+'\n\n',delay_factor=5)
            # Configuration_Output=net_connect.send_command_timing("show run "+'\n\n' ,delay_factor=5,strip_prompt=False,strip_command=False)
            # Configuration_Output+=net_connect.send_command_timing("show ip inte br "+'\n\n',delay_factor=5,strip_prompt=False,strip_command=False)
            # Configuration_Switch=net_connect.send_command_timing("show fex  "+'\n\n',delay_factor=5,strip_prompt=False,strip_command=False)
            # Configuration_Output+=net_connect.send_command_timing("show cdp neighbors detail "+'\n\n',delay_factor=5,strip_prompt=False,strip_command=False)
            # Configuration_Switch+=net_connect.send_command_timing("show interfaces status  "+'\n\n',delay_factor=5,strip_prompt=False,strip_command=False)
            # Configuration_Output+=net_connect.send_command_timing("show inter desc "+'\n\n',delay_factor=5,strip_prompt=False,strip_command=False)
            # Configuration_Router=net_connect.send_command_timing("show ip ospf neighbor "+'\n\n',delay_factor=5,strip_prompt=False,strip_command=False)
            # Configuration_Output+=net_connect.send_command_timing("show version "+'\n\n',delay_factor=5,strip_prompt=False,strip_command=False)
            # Configuration_Output+=net_connect.send_command_timing("show cdp neighbors "+'\n\n',delay_factor=5,strip_prompt=False,strip_command=False)

            ###########################################################################################################
            ############################ Use TEXTFSM Template to get Show version ############################
            ###########################################################################################################
            try:
                # Show_Version_TEXTFSM_List=net_connect.send_command_timing("show version "+'\n\n'  ,strip_prompt=False,strip_command=False, use_textfsm=True, textfsm_template="/home/khayat/Textfsm_Templates/cisco_ios_show_version.textfsm")
                # Test_Expect=net_connect.send_command("show ip inte br "+'\n\n' ,strip_prompt=False,strip_command=False)
                # print ("\t\tTest_Expect")
                # print (Test_Expect)
                Show_Version_TEXTFSM_List = net_connect.send_command_timing(
                    "show version " + '\n\n',
                    strip_prompt=False,
                    strip_command=False,
                    use_textfsm=True)
                Show_Version_TEXTFSM_Dict = Show_Version_TEXTFSM_List[
                    0]  # this is because the output is in list then in Dict
                # print (type(Show_Version_TEXTFSM_List))
                # print ((Show_Version_TEXTFSM_List))
                # print (type(Show_Version_TEXTFSM_Dict))
                # print ((Show_Version_TEXTFSM_Dict))
                # print ("\n\n\n")
                # print ("\t\tConfiguration_Output_TEXTFSM")
                # for k,v in Show_Version_TEXTFSM_Dict.items() :
                # 	print (f"{k} :: {v}")

                if Show_Version_TEXTFSM_Dict["hardware"]:
                    Hardware_IP = "\t\t" + str(
                        Show_Version_TEXTFSM_Dict["hardware"]
                        [0]) + f"		{ip}___" + str(
                            Show_Version_TEXTFSM_Dict["hostname"])
                    All_Hardware_Module_List.append(Hardware_IP)
                else:
                    Hardware_IP_Empty_List.append(ip + "   Hardware Empty")
                Hostname_Output = ip + ".__" + str(
                    Show_Version_TEXTFSM_Dict["hostname"])
                Worked_IPs_Old.append(ip)

            except Exception as e:
                print('Exception in show version\t' + ip)
                FailedIps.append(ip + "   Exception in show version")
                IPs_ForIteration.append(ip)

    ###########################################################################################################

    # Hostname_Output=net_connect.send_command("show run | i hostname"+'\n\n')

    # Configuration_Output+=net_connect.send_command_timing("show ip inte br "+'\n\n',strip_prompt=False,strip_command=False)

            print(f"This is after getting SHOW for IP\t{ip}")

            # Hostname_Output=net_connect.send_command("show run | i hostname"+'\n\n',delay_factor=5)

            ###########################################################################################################
            ##################      Get each interfaces status using Script     ##################################################
            ###########################################################################################################
            # List_Of_Inter=net_connect.send_command_timing("show interface status "+'\n\n')
            # # print ("\t\tList_Of_Inter")
            # List_of_Lines= Get_All_Inter(List_Of_Inter)
            # print ("\t\tList_of_Lines\n")
            # print (List_of_Lines)
            # print ("\t\tGet_Ports_Status")
            # Returned_List=Get_Ports_Status(List_of_Lines)

            # for i in Returned_List :
            #   print (f"key\t{i}\tValue\t{Returned_List.get(i)} ")

            # ###########################################################################################################
            # ##################        Get each interfaces IP using Script     ##################################################
            # ###########################################################################################################
            # IPs_All_Interfaces=net_connect.send_command_timing("show ip interface br "+'\n\n')

            # Inter_IPs= Get_Interfaces_IP(IPs_All_Interfaces)

            # for x in Inter_IPs :
            #   if x[-1] =="up" and x[-2]=="up" :
            #       print (x)
            #       print (x[1])

            ##################################################################
            ########### Check if in config mode or not to exit config mode
            ##################################################################
            if not net_connect.check_config_mode():
                net_connect.config_mode()
                print("After entering config " + str(ip))
            print("After checking config to perform configuration commands  " +
                  str(ip))

            ######################################################################
            ################ Set list of configuration  ###########################
            ######################################################################
            # List_cmd=[f"inte {Returned_List["disabled"][0]}","no shutd","ip add 192.168.100.100 255.255.255.0"]
            # print ("Returned_List[disabled][0]")
            # print (Returned_List.get("disabled")[0])
            # Temp=str(Returned_List.get("disabled")[0])
            # List_cmd=[f"inte {Temp}","no shutd"]
            # Output_Setting_Inter=net_connect.send_config_set(config_commands=List_cmd)
            # print ("Output_Setting_Inter")
            # print (Output_Setting_Inter)

            ##################################################################
            ########### Check if in config mode or not to exit config mode
            ##################################################################
            if net_connect.check_config_mode():
                net_connect.exit_config_mode()
                print("After exiting config " + str(ip))
            print("After checking config for CDP command\t" + str(ip))

            ###########################################################################################################
            ##################      Add new IPs from CDP Command     ##################################################
            ###########################################################################################################

            ###############################################################################
            ######################## Using Script for cdp neighbors to get New IPs
            ###############################################################################

            # CDP_ALL=net_connect.send_command_timing("show cdp neighbors detail | i IP address: "+'\n\n')
            # print ("\t\tGet_CDP_Neighbors")
            # num_New = list(num_New) + list(Get_CDP_Neighbors (CDP_ALL , num))

            ###############################################################################
            ######################## Using TextFSM for cdp neighbors
            ###############################################################################
            try:
                Show_CDP_Details_TEXTFSM_List = net_connect.send_command_timing(
                    "show cdp neighbors detail " + '\n\n',
                    strip_prompt=False,
                    strip_command=False,
                    use_textfsm=True)
                for n in Show_CDP_Details_TEXTFSM_List:
                    Show_CDP_Details_TEXTFSM_Dict = n  # this is because the output is in list then in Dict
                    # print (type(Show_CDP_Details_TEXTFSM_List))
                    # print (Show_CDP_Details_TEXTFSM_List)
                    # print (type(Show_CDP_Details_TEXTFSM_Dict))
                    # print (Show_CDP_Details_TEXTFSM_Dict)
                    # print (type(Show_CDP_Details_TEXTFSM_Dict["management_ip"]))
                    # print (Show_CDP_Details_TEXTFSM_Dict["management_ip"])
                    if "172." in Show_CDP_Details_TEXTFSM_Dict[
                            "management_ip"]:
                        if Show_CDP_Details_TEXTFSM_Dict[
                                "management_ip"] not in num and Show_CDP_Details_TEXTFSM_Dict[
                                    "management_ip"] not in num_New and Show_CDP_Details_TEXTFSM_Dict[
                                        "management_ip"] not in Worked_IPs_Old:
                            num_New.append(
                                Show_CDP_Details_TEXTFSM_Dict["management_ip"])

            except Exception as e:
                print('Exception in show cdp neighbors \t' + ip)
                FailedIps.append(ip + "   Exception in show cdp neighbors ")
                IPs_ForIteration.append(ip)

        ###########################################################################################################
        ################    Example on confirmation message Function
        ###########################################################################################################

        # if ip =="192.168.233.13":
        #       print (str (SpecialConfirmation("crypto key generate rsa general-keys" ,"modulus" ,"1024")))

        ###########################################################################################################
        ###########################################################################################################
            if net_connect.check_config_mode():
                net_connect.exit_config_mode()
            print("After last check config " + str(ip))

            ################################################################################
            ####################### Test Ping For Rang Of IP  ##############################
            ################################################################################

            # Active_ping_ip=[]
            # InActive_ping_ip=[]
            # Sub_Ip_ping="2.0.32."
            # for x in range(1,255) :
            # 	print (x)
            # 	Ip_ping=Sub_Ip_ping+str(x)
            # 	ping_result=net_connect.send_command_timing("ping  "+Ip_ping+'\n\n' ,strip_prompt=False,strip_command=False)
            # 	# print (ping_result)
            # 	# ping_is_successful(ping_result)
            # 	# print (ping_is_successful(ping_result))
            # 	# print (type(ping_is_successful(ping_result)))

            # 	if ping_is_successful(ping_result) :
            # 		Active_ping_ip.append(Ip_ping)
            # 	else :
            # 		InActive_ping_ip.append(Ip_ping)
            # print ("Active_ping_ip")
            # for x in Active_ping_ip :
            # 	print (x)

            # print ("\n\n\nInActive_ping_ip")
            # for x in InActive_ping_ip :
            # 	print (x)

            ############### Append Configuration Variables to Global Variable ##########

            # Conf_Variables.append(Hostname_Output)
            # print (Configuration_Output)
            # Conf_Variables.append(Configuration_Output)
            ############### Search in Configuration if any command error and return its IP ################
            for y in Conf_Variables:
                if "% Invalid input detected at '^' marker." in y:
                    FailedIps.append(ip + "   Invalid input")
#########################################################################################################
            Hostname_Output_list.append(Hostname_Output)
            test = Configuration_Switch
            test += Configuration_Output
            test += Configuration_Router
            Configuration_Output_list.append(test)

            Configuration_Output_ID2_list.append(Configuration_Output_ID2)
            Configuration_Output_ID254_list.append(Configuration_Output_ID254)

            ############### SAVE Output IN FILES  #######################
            Global_Output.append(Hostname_Output)
            print("Exiting  " + str(ip))
            net_connect.disconnect()
            print("After Exiting  " + str(ip))


################### Exception ###################################

        except (NetMikoAuthenticationException
                ) as netmikoAuthenticationException:
            # print ('Authentication Failure\t' + ip)
            print(
                str(User_Pass_Num) + "   " +
                str(Username_Device[User_Pass_Num]) +
                " failed Authentication\t" + ip)
            ################ Print error from msg from the main Lib
            print(
                f"netmikoAuthenticationException : {netmikoAuthenticationException}\n"
            )
            User_Pass_Num += 1
            # If it tried all users and pass and failed add it to failedIps
            if User_Pass_Num >= len(Username_Device):
                FailedIps.append(ip + "   Authentication Error ")
                IPs_ForIteration.append(ip)
            # if User_Pass_Num < len(Username_Device) :
            #       print("this is Authentication  "+str(ip)+" Device_Type "+str(Device_Type[Device_Type_Num])+" Username_Device " +str(Username_Device[User_Pass_Num])+" Passowrd_Device " +str(Passowrd_Device[User_Pass_Num]))
        # Recursive function
            return ConfigurationTest(ip, Device_Type_Num, User_Pass_Num,
                                     Passowrd_Enable_Num)

        except (ValueError):
            print(str(Passowrd_Enable_Num) + "\tEnable Authentication\t" + ip)
            Passowrd_Enable_Num += 1
            if Passowrd_Enable_Num >= len(Passowrd_Device_Enable):
                FailedIps.append(ip + "   Enable Authentication Error ")
                IPs_ForIteration.append(ip)
            return ConfigurationTest(ip, Device_Type_Num, User_Pass_Num,
                                     Passowrd_Enable_Num)

        except socket_error as socket_err:
            ################ Print error from msg from the main Lib
            print(
                f"Socket Error: \n{socket_err}\t for IP {ip}  trying another type of Connection\n"
            )
            print("Continue")
            if '111' in f"Type {socket_err}":
                Device_Type_Num += 1
                if Device_Type_Num >= len(Device_Type):
                    FailedIps.append(ip + "   Socket or connection type Error")
                    IPs_ForIteration.append(ip)
                return ConfigurationTest(ip, Device_Type_Num, User_Pass_Num,
                                         Passowrd_Enable_Num)
            if '113' in f"Type {socket_err}":
                FailedIps.append(ip + "   No route to the host")
                IPs_ForIteration.append(ip)
                return ConfigurationTest_Boolen == 1
            FailedIps.append(ip + "   Socket or connection type Error")
            IPs_ForIteration.append(ip)
            return ConfigurationTest_Boolen == 1

        except (NetMikoTimeoutException) as netmikoTimeoutException:
            # print ('Timeout  Failure\t' + ip)
            print(str(Device_Type_Num) + "\tTimeoutException\t" + ip)
            ################ Print error from msg from the main Lib
            print(f"netmikoTimeoutException : \n{netmikoTimeoutException}\n")
            Device_Type_Num += 1
            if Device_Type_Num >= len(Device_Type):
                FailedIps.append(ip + "   Timeout Error")
                IPs_ForIteration.append(ip)
            # if  Device_Type_Num < len(Device_Type) :
            #       print("this is Timeout "+str(ip)+" Device_Type "+str(Device_Type[Device_Type_Num])+" Username_Device " +str(Username_Device[User_Pass_Num])+" Passowrd_Device " +str(Passowrd_Device[User_Pass_Num]))
            return ConfigurationTest(ip, Device_Type_Num, User_Pass_Num,
                                     Passowrd_Enable_Num)

        # except (paramiko.ssh_exception.SSHException) as sshException :
        except (SSHException) as sshException:
            # print ('SSH  Failure\t' + ip)
            print(str(Device_Type_Num) + "\tSSHException\t" + ip + "\n")
            ################ Print error from msg from the main Lib
            print(
                f"Unable to establish SSH connection: \n{sshException}\t for IP {ip}\n"
            )
            Device_Type_Num += 1
            if Device_Type_Num >= len(Device_Type):
                FailedIps.append(ip + "   SSHException Error ")
                IPs_ForIteration.append(ip)
            # if  Device_Type_Num < len(Device_Type) :
            #       print("this is SSHException "+str(ip)+" Device_Type "+str(Device_Type[Device_Type_Num])+" Username_Device " +str(Username_Device[User_Pass_Num])+" Passowrd_Device " +str(Passowrd_Device[User_Pass_Num]))
            return ConfigurationTest(ip, Device_Type_Num, User_Pass_Num,
                                     Passowrd_Enable_Num)

        except (ValueError):
            print(
                str(Passowrd_Enable_Num) + "   " +
                str(Passowrd_Device_Enable[Passowrd_Enable_Num]) +
                " Failed Enable Authentication\t" + ip)
            Passowrd_Enable_Num += 1
            if Passowrd_Enable_Num >= len(Passowrd_Device_Enable):
                FailedIps.append(ip + "   Enable Authentication Error ")
                IPs_ForIteration.append(ip)
            return ConfigurationTest(ip, Device_Type_Num, User_Pass_Num,
                                     Passowrd_Enable_Num)

        except (EOFError) as eof_Error:
            ################ Print error from msg from the main Lib
            print(f"eof_Error : \n{eof_Error}\n")
            # print ('End of File wihle attempting device\t' +ip)
            FailedIps.append(ip + "   EOFError")
            IPs_ForIteration.append(ip)
            # print("this is EOFError "+str(ip)+" Device_Type "+str(Device_Type[Device_Type_Num])+" Username_Device " +str(Username_Device[User_Pass_Num])+" Passowrd_Device " +str(Passowrd_Device[User_Pass_Num]))
            return ConfigurationTest_Boolen == 1

    ###################################################################
    ######### if you want to show error , comment next lines if you want to show which Ips have error remove comment  ##############
    ###################################################################
    # except Exception as e:
    #       # print ('End of File wihle attempting device\t' +ip)
    #       FailedIps.append(ip+"   Exception as e")
    #       # print("this is EOFError "+str(ip)+" Device_Type "+str(Device_Type[Device_Type_Num])+" Username_Device " +str(Username_Device[User_Pass_Num])+" Passowrd_Device " +str(Passowrd_Device[User_Pass_Num]))
    #       return ConfigurationTest_Boolen==1

    ####################################################################

    return ConfigurationTest_Boolen == 1
Ejemplo n.º 52
0
    'device_type': 'cisco_ios',
    'ip': '50.76.53.27',
    'username': '******',
    'password': passwd,
    'port': 8022,
}
juniper_srx= {
    'device_type': 'juniper',
    'ip': '50.76.53.27',
    'username': '******',
    'password': passwd,
    'port': 9822,
}
pynet_rtr2= ConnectHandler(**pynet2)
pynet_rtr1= ConnectHandler(**pynet1)
pynet_juniper= ConnectHandler(**juniper_srx)
pynet_rtr2.config_mode()
print pynet_rtr2.check_config_mode()
print "sh arp rtr1:\n"
outp=pynet_rtr1.send_command("show arp")
print outp
print "sh arp juniper:\n"
outp=pynet_juniper.send_command("show arp")
print outp
pynet_rtr2.send_command("logging buffered 40960")

    #tim2.sleep(1)
    


Ejemplo n.º 53
0
    'port':8022
    }
juniper_srx={
    'device_type':'juniper',
    'ip':'50.76.53.27',
    'username':'******',
    'password':password,
    'secret':'',
    'port':9822
    }

pynet_rtr1=ConnectHandler(**pynet1)
pynet_rtr2=ConnectHandler(**pynet2)
srx=ConnectHandler(**juniper_srx)

print pynet_rtr1.find_prompt()
print pynet_rtr2.find_prompt()
print srx.find_prompt()

pynet_rtr1.config_mode()
print pynet_rtr1.check_config_mode()
print pynet_rtr1.find_prompt()
pynet_rtr1.send_command("end")
print pynet_rtr1.send_command("sh version")
list_of_command=['logging buffer 9800','logging buffer 1000']
print pynet_rtr1.send_config_set(list_of_command)
time.sleep(2)
print pynet_rtr1.find_prompt()
print pynet_rtr1.send_command("sh logging | inc Log Buffer")
print pynet_rtr1.send_config_from_file(config_file='test.txt')
	'password': '******',
}

pynetrtr2 = {
	'device_type': 'cisco_ios',
	'ip': '50.76.53.27',
	'username': '******',
	'password': '******',
	'port': 8022
}

srx = {
	'device_type': 'juniper',
	'ip': '50.76.53.27',
	'username': '******',
	'password': '******',
	'port': 9822
}

rtr2 = ConnectHandler(**pynetrtr2)
# passes in dictionary key values into the function

output = rtr2.find_prompt()
print output

output = rtr2.config_mode()
print output

output = rtr2.check_config_mode()
print output
Ejemplo n.º 55
0
class NetworkDeviceIOS(NetworkDevice):

    #---------------------------------------------------------------------------
    def __init__(self, name, ip, user='******', pw='cisco', secret=''):
        NetworkDevice.__init__(self, name, ip, user, pw)
        self.secret = secret
        self.device = {
            'device_type': 'cisco_ios',
            'ip': self.ip_address,
            'username': self.username,
            'password': self.password,
            'secret': self.secret,
            'port': 22,
        }
        self.session = None
        logger.info('devclass: created IOS device: %s %s', name, ip)

#---------------------------------------------------------------------------

    def connect(self):
        try:
            print('--- connecting IOS: telnet: ' + self.ip_address + ' for: ' +
                  self.username)
            self.session = ConnectHandler(**self.device)
            logger.info('devclass: successful login at: %s for user: %s',
                        self.ip_address, self.username)
            return self.session
        except Exception as err:
            logger.error('devclass: Erro no login at: %s for user: %s',
                         self.ip_address, self.username)
            print('Ocorreu um Erro: ' + str(err))
            raise Exception('Erro em devclass.connect')

#---------------------------------------------------------------------------

    def disconnect(self):
        if self.esta_connectado():
            print('--- disconnecting IOS: telnet: ' + self.ip_address +
                  ' for: ' + self.username)
            self.session.disconnect()
            logger.info('devclass: successful logoff at: %s for user: %s',
                        self.ip_address, self.username)
        else:
            logger.warn('devclass: --- Erro ao desconectar.')
            print("Não há sessão para desconectar!")

#---------------------------------------------------------------------------

    def get_interfaces(self):
        if self.esta_connectado():
            self.interfaces = self.session.send_command("show int status")
            logger.info(
                'devclass: successful get_interfaces at: %s for user: %s',
                self.ip_address, self.username)
            return self.interfaces
        else:
            logger.error(
                'devclass: Erro ao executar devclass.get_interfaces() - Sessão não estabelecida. at: %s for user: %s',
                self.ip_address, self.username)
            raise Exception(
                'Erro ao executar devclass.get_interfaces() - Sessao nao estabelecida.'
            )
            return "Erro "
#---------------------------------------------------------------------------

    def get_int_connected(self):
        if self.esta_connectado():
            output = self.session.send_command("show int status | i cted")
            logger.info(
                'devclass: successful get_int_connected at: %s for user: %s',
                self.ip_address, self.username)
            return output
        else:
            logger.error(
                'devclass: Erro ao executar devclass.get_int_connected() - Sessão não estabelecida. at: %s for user: %s',
                self.ip_address, self.username)
            raise Exception(
                'Erro ao executar devclass.get_int_connected() - Sessao nao estabelecida.'
            )
            return "erro"

#---------------------------------------------------------------------------

    def do_wr(self):
        if self.esta_connectado():
            output = self.session.send_command('write memory')
            logger.info('devclass: successful do_wr at: %s for user: %s',
                        self.ip_address, self.username)
            return output
        else:
            logger.error(
                'devclass: Erro ao executar devclass.do_wr() - Sessão não estabelecida. at: %s for user: %s',
                self.ip_address, self.username)
            raise Exception(
                'Erro ao executar devclass.do_wr() - Sessao nao estabelecida.')
#---------------------------------------------------------------------------

    def config_mode(self):
        if self.esta_connectado():
            output = self.session.config_mode()
            logger.info(
                'devclass: successful config_mode() at: %s for user: %s',
                self.ip_address, self.username)
            return output
        else:
            logger.error(
                'devclass: Erro ao executar devclass.config_mode() - Sessão não estabelecida. at: %s for user: %s',
                self.ip_address, self.username)
            raise Exception(
                'Erro ao executar devclass.config_mode() - Sessao nao estabelecida.'
            )
#---------------------------------------------------------------------------

    def exit_config_mode(self):
        if self.esta_connectado():
            output = self.sessionc.exit_config_mode()
            logger.info(
                'devclass: successful exit_config_mode() at: %s for user: %s',
                self.ip_address, self.username)
            return output
        else:
            logger.error(
                'devclass: Erro ao executar devclass.exit_config_mode() - Sessão não estabelecida. at: %s for user: %s',
                self.ip_address, self.username)
            raise Exception(
                'Erro ao executar devclass.exit_config_mode() - Sessao nao estabelecida.'
            )
#---------------------------------------------------------------------------

    def check_config_mode(self):
        if self.esta_connectado():
            output = self.session.check_config_mode()
            logger.info(
                'devclass: successful check_config_mode() at: %s for user: %s',
                self.ip_address, self.username)
            return output
        else:
            logger.error(
                'devclass: Erro ao executar devclass.check_config_mode() - Sessão não estabelecida. at: %s for user: %s',
                self.ip_address, self.username)
            raise Exception(
                'Erro ao executar devclass.check_config_mode() - Sessao nao estabelecida.'
            )
#---------------------------------------------------------------------------

    def enable(self):
        if self.esta_connectado():
            output = self.session.enable()
            logger.info('devclass: successful enable() at: %s for user: %s',
                        self.ip_address, self.username)
            return output
        else:
            logger.error(
                'devclass: Erro ao executar devclass.enable() - Sessão não estabelecida. at: %s for user: %s',
                self.ip_address, self.username)
            raise Exception(
                'Erro ao executar devclass.enable() - Sessao nao estabelecida.'
            )
#---------------------------------------------------------------------------

    def exit_enable_mode(self):
        if self.esta_connectado():
            output = self.session.exit_enable_mode()
            logger.info(
                'devclass: successful exit_enable_mode() at: %s for user: %s',
                self.ip_address, self.username)
            return output
        else:
            logger.error(
                'devclass: Erro ao executar devclass.exit_enable_mode() - Sessão não estabelecida. at: %s for user: %s',
                self.ip_address, self.username)
            raise Exception(
                'Erro ao executar devclass.exit_enable_mode() - Sessao nao estabelecida.'
            )
#---------------------------------------------------------------------------

    def find_prompt(self):
        if self.esta_connectado():
            output = self.session.find_prompt()
            logger.info(
                'devclass: successful find_prompt() at: %s for user: %s',
                self.ip_address, self.username)
            return output
        else:
            logger.error(
                'devclass: Erro ao executar devclass.find_prompt() - Sessão não estabelecida. at: %s for user: %s',
                self.ip_address, self.username)
            raise Exception(
                'Erro ao executar devclass.find_prompt() - Sessao nao estabelecida.'
            )
#---------------------------------------------------------------------------

    def send_command(self, arguments):
        if self.esta_connectado():
            output = self.session.send_command(arguments)
            logger.info(
                'devclass: successful send_command() at: %s for user: %s',
                self.ip_address, self.username)
            return output
        else:
            logger.error(
                'devclass: Erro ao executar devclass.send_command() - Sessão não estabelecida. at: %s for user: %s',
                self.ip_address, self.username)
            raise Exception(
                'Erro ao executar devclass.send_command() - Sessao nao estabelecida.'
            )
#---------------------------------------------------------------------------

    def send_config_set(self, arguments_list):
        if self.esta_connectado():
            output = self.session.send_config_set(arguments_list)
            logger.info(
                'devclass: successful send_config_set() at: %s for user: %s',
                self.ip_address, self.username)
            return output
        else:
            logger.error(
                'devclass: Erro ao executar devclass.send_config_set() - Sessão não estabelecida. at: %s for user: %s',
                self.ip_address, self.username)
            raise Exception(
                'Erro ao executar devclass.send_config_set() - Sessao nao estabelecida.'
            )
#---------------------------------------------------------------------------

    def send_config_from_file(self, file):
        if self.esta_connectado():
            output = self.session.send_config_from_file(file)
            logger.info(
                'devclass: successful send_config_from_file() at: %s for user: %s',
                self.ip_address, self.username)
            return output
        else:
            logger.error(
                'devclass: Erro ao executar devclass.send_config_from_file() - Sessão não estabelecida. at: %s for user: %s',
                self.ip_address, self.username)
            raise Exception(
                'Erro ao executar devclass.send_config_from_file() - Sessao nao estabelecida.'
            )
#---------------------------------------------------------------------------

    def esta_connectado(self):
        if self.session != None:
            return True
        else:
            return False
#---------------------------------------------------------------------------

    def debug_devclass(self):
        filename_log = self.ip_address + '_.log'
        logging.basicConfig(filename=filename_log,
                            format='%(asctime)s - %(levelname)s - %(message)s',
                            level=logging.DEBUG)
        debugClass = logging.getLogger("netmiko")
#---------------------------------------------------------------------------

    def get_hostname(self):
        if self.esta_connectado():
            output = self.session.send_command("show conf | i hostname")
            logger.info(
                'devclass: successful get_hostname at: %s for user: %s',
                self.ip_address, self.username)
            hostname = (output.split())[1]
            return hostname
        else:
            logger.error(
                'devclass: Erro ao executar devclass.get_hostname() - Sessão não estabelecida. at: %s for user: %s',
                self.ip_address, self.username)
            raise Exception(
                'Erro ao executar devclass.get_hostname() - Sessao nao estabelecida.'
            )
            return "Erro "
#---------------------------------------------------------------------------

    def get_nbem(self):
        if self.esta_connectado():
            output = self.session.send_command("show run | i chassis")
            logger.info('devclass: successful get_nbem at: %s for user: %s',
                        self.ip_address, self.username)
            output = (output.split())[2]
            return output
        else:
            logger.error(
                'devclass: Erro ao executar devclass.get_nbem() - Sessão não estabelecida. at: %s for user: %s',
                self.ip_address, self.username)
            raise Exception(
                'Erro ao executar devclass.get_nbem() - Sessao nao estabelecida.'
            )

    #---------------------------------------------------------------------------
    def get_serial(self):
        if self.esta_connectado():
            output = self.session.send_command(
                "show version | i System [s,S]erial")
            logger.info('devclass: successful get_serial at: %s for user: %s',
                        self.ip_address, self.username)
            outputlines = output.splitlines()
            serial = []
            for line in outputlines:
                serial.append((line.split(": "))[1])
            return serial
        else:
            logger.error(
                'devclass: Erro ao executar devclass.get_serial() - Sessão não estabelecida. at: %s for user: %s',
                self.ip_address, self.username)
            raise Exception(
                'Erro ao executar devclass.get_serial() - Sessao nao estabelecida.'
            )


#---------------------------------------------------------------------------
#retorna o MAC pelo IP

    def busca_mac(self, end_ip):
        if self.esta_connectado():
            output = self.session.send_command("show arp | i %s" % end_ip)
            logger.info('devclass: successful busca_mac at: %s for user: %s',
                        self.ip_address, self.username)
            #output = (output.split())[2]
            return output
        else:
            logger.error(
                'devclass: Erro ao executar devclass.busca_mac() - Sessão não estabelecida. at: %s for user: %s',
                self.ip_address, self.username)
            raise Exception(
                'Erro ao executar devclass.busca_mac() - Sessao nao estabelecida.'
            )

    #---------------------------------------------------------------------------
Ejemplo n.º 56
0
#!/usr/bin/env python
from __future__ import print_function
from netmiko import ConnectHandler

pynet2 = {
    'device_type': 'cisco_ios',
    'ip': '184.105.247.71',
    'username': '******',
    'password': '******',
    'port': 22
}

net_connect = ConnectHandler(**pynet2)
net_connect.config_mode()

if net_connect.check_config_mode() is True:
    print(net_connect.find_prompt())

net_connect.exit_config_mode()
net_connect.disconnect()
Ejemplo n.º 57
0

from netmiko import ConnectHandler

pynet2 = {
    'device_type': 'cisco_ios',
    'ip': '184.105.247.71',
    'username': '******',
    'password': '******',
}

pynet_rtr2 = ConnectHandler(**pynet2)
pynet_rtr2.config_mode()
pynet_rtr2.check_config_mode()
pynet_rtr2.exit_config_mode()
pynet_rtr2.disconnect()