Ejemplo n.º 1
0
class SshDevice(Device):
    """Class for communicating with switches over SSH.
    """
    def __init__(self, hostname, username, password):
        try:
            self.device = ConnectHandler(device_type='cisco_nxos',
                                         ip=hostname,
                                         username=username,
                                         password=password,
                                         verbose=False)
        except Exception as e:
            print 'Error SSHing to device at {}'.format(hostname)
            if isinstance(e, NetMikoAuthenticationException):
                print 'This may not be a Cisco device, or there may an authentication issue.'
            elif isinstance(e, NetMikoTimeoutException):
                print 'Could not connect to device'

            sys.exit()

    def show_command(self, cmd):
        if not self.device.check_enable_mode():
            self.device.enable()
        return self.device.send_command(cmd)

    def disconnect(self):
        self.device.disconnect()
Ejemplo n.º 2
0
def do_netmiko(switches, commands=commands):
    """Iterates commands over a list of switches
   commands='command 1'
   commands=['command 1', 'command 2']
   This can be a list or a string"""
    device = {
        'device_type': 'arista_eos',
        'ip': switches,
        'username': args.username,
        'password': args.password,
        'port': 22,
    }
    net_connect = ConnectHandler(**device)

    # Checking prompt for "admin" since 'fc' can be either Brocade or Cisco
    # Return here if we find naming scheme for FC.
    # You may not need this
    if re.findall(device['username'], net_connect.find_prompt()):
        return

    net_connect.enable()
    output = net_connect.send_config_set(commands)
    rc = net_connect.check_enable_mode()  # Works for Arista and Cisco
    ip = net_connect.ip
    net_connect.disconnect()
    return {'output': output, 'rc': rc, 'ip': ip}
Ejemplo n.º 3
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: "******"username": username,
        "use_keys": True,
        "ip": hostname,
        "device_type": "ovs_linux",
        "key_file": "/home/{}/.ssh/test_rsa".format(username),
        "verbose": False,
    }

    net_connect = ConnectHandler(**linux_test)
    print()
    print(net_connect.find_prompt())

    # Test enable mode
    print()
    print("***** 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.º 4
0
class IOSDevice(BaseDevice):
    def __init__(self, host, username, password, secret='', port=22, **kwargs):
        super(IOSDevice, self).__init__(host,
                                        username,
                                        password,
                                        vendor='cisco',
                                        device_type=IOS_SSH_DEVICE_TYPE)

        self.native = None

        self.host = host
        self.username = username
        self.password = password
        self.secret = secret
        self.port = int(port)
        self.global_delay_factor = kwargs.get('global_delay_factor', 1)
        self.delay_factor = kwargs.get('delay_factor', 1)
        self._connected = False
        self.open()

    def open(self):
        if self._connected:
            try:
                self.native.find_prompt()
            except:
                self._connected = False

        if not self._connected:
            self.native = ConnectHandler(
                device_type='cisco_ios',
                ip=self.host,
                username=self.username,
                password=self.password,
                port=self.port,
                global_delay_factor=self.global_delay_factor,
                secret=self.secret,
                verbose=False)
            self._connected = True

    def close(self):
        if self._connected:
            self.native.disconnect()
            self._connected = False

    def _enter_config(self):
        self._enable()
        self.native.config_mode()

    def _enable(self):
        self.native.exit_config_mode()
        if not self.native.check_enable_mode():
            self.native.enable()

    def _send_command(self, command, expect=False, expect_string=''):
        if expect:
            if expect_string:
                response = self.native.send_command_expect(
                    command, expect_string=expect_string)
            else:
                response = self.native.send_command_expect(command)
        else:
            response = self.native.send_command_timing(command)

        if '% ' in response or 'Error:' in response:
            raise CommandError(command, response)

        return response

    def config(self, command):
        self._enter_config()
        self._send_command(command)
        self.native.exit_config_mode()

    def config_list(self, commands):
        self._enter_config()
        entered_commands = []
        for command in commands:
            entered_commands.append(command)
            try:
                self._send_command(command)
            except CommandError as e:
                raise CommandListError(entered_commands, command,
                                       e.cli_error_msg)
        self.native.exit_config_mode()

    def show(self, command, expect=False, expect_string=''):
        self._enable()
        return self._send_command(command,
                                  expect=expect,
                                  expect_string=expect_string)

    def show_list(self, commands):
        self._enable()

        responses = []
        entered_commands = []
        for command in commands:
            entered_commands.append(command)
            try:
                responses.append(self._send_command(command))
            except CommandError as e:
                raise CommandListError(entered_commands, command,
                                       e.cli_error_msg)

        return responses

    def save(self, filename='startup-config'):
        command = 'copy running-config %s' % filename
        # Changed to send_command_timing to not require a direct prompt return.
        self.native.send_command_timing(command)
        # If the user has enabled 'file prompt quiet' which dose not require any confirmation or feedback. This will send return without requiring an OK.
        # Send a return to pass the [OK]? message - Incease delay_factor for looking for response.
        self.native.send_command_timing('\n', delay_factor=2)
        # Confirm that we have a valid prompt again before returning.
        self.native.find_prompt()
        return True

    def _file_copy_instance(self, src, dest=None, file_system='flash:'):
        if dest is None:
            dest = os.path.basename(src)

        fc = FileTransfer(self.native, src, dest, file_system=file_system)
        return fc

    def file_copy_remote_exists(self, src, dest=None, file_system='flash:'):
        fc = self._file_copy_instance(src, dest, file_system=file_system)

        self._enable()
        if fc.check_file_exists() and fc.compare_md5():
            return True
        return False

    def file_copy(self, src, dest=None, file_system='flash:'):
        fc = self._file_copy_instance(src, dest, file_system=file_system)
        self._enable()
        #        if not self.fc.verify_space_available():
        #            raise FileTransferError('Not enough space available.')

        try:
            fc.enable_scp()
            fc.establish_scp_conn()
            fc.transfer_file()
        except:
            raise FileTransferError
        finally:
            fc.close_scp_chan()

    def reboot(self, timer=0, confirm=False):
        if confirm:

            def handler(signum, frame):
                raise RebootSignal('Interrupting after reload')

            signal.signal(signal.SIGALRM, handler)
            signal.alarm(10)

            try:
                if timer > 0:
                    first_response = self.show('reload in %d' % timer)
                else:
                    first_response = self.show('reload')

                if 'System configuration' in first_response:
                    self.native.send_command_timing('no')

                self.native.send_command_timing('\n')
            except RebootSignal:
                signal.alarm(0)

            signal.alarm(0)
        else:
            print('Need to confirm reboot with confirm=True')

    def _is_catalyst(self):
        return self.facts['model'].startswith('WS-')

    def set_boot_options(self, image_name, **vendor_specifics):
        if self._is_catalyst():
            self.config('boot system flash:/%s' % image_name)
        else:
            self.config_list(
                ['no boot system',
                 'boot system flash %s' % image_name])

    def get_boot_options(self):
        if self._is_catalyst():
            show_boot_out = self.show('show boot')
            boot_path_regex = r'BOOT path-list\s+:\s+(\S+)'
            boot_path = re.search(boot_path_regex, show_boot_out).group(1)
            boot_image = boot_path.replace('flash:/', '')
            return dict(sys=boot_image)
        else:
            show_boot_out = self.show('show run | inc boot')
            boot_path_regex = r'boot system flash (\S+)'

            match = re.search(boot_path_regex, show_boot_out)
            if match:
                boot_image = match.group(1)
            else:
                boot_image = None
            return dict(sys=boot_image)

    def backup_running_config(self, filename):
        with open(filename, 'w') as f:
            f.write(self.running_config)

    def _uptime_components(self, uptime_full_string):
        match_days = re.search(r'(\d+) days?', uptime_full_string)
        match_hours = re.search(r'(\d+) hours?', uptime_full_string)
        match_minutes = re.search(r'(\d+) minutes?', uptime_full_string)

        days = int(match_days.group(1)) if match_days else 0
        hours = int(match_hours.group(1)) if match_hours else 0
        minutes = int(match_minutes.group(1)) if match_minutes else 0

        return days, hours, minutes

    def _uptime_to_string(self, uptime_full_string):
        days, hours, minutes = self._uptime_components(uptime_full_string)
        return '%02d:%02d:%02d:00' % (days, hours, minutes)

    def _uptime_to_seconds(self, uptime_full_string):
        days, hours, minutes = self._uptime_components(uptime_full_string)

        seconds = days * 24 * 60 * 60
        seconds += hours * 60 * 60
        seconds += minutes * 60

        return seconds

    def _interfaces_detailed_list(self):
        ip_int_br_out = self.show('show ip int br')
        ip_int_br_data = get_structured_data(
            'cisco_ios_show_ip_int_brief.template', ip_int_br_out)

        return ip_int_br_data

    def _show_vlan(self):
        show_vlan_out = self.show('show vlan')
        show_vlan_data = get_structured_data('cisco_ios_show_vlan.template',
                                             show_vlan_out)

        return show_vlan_data

    def _raw_version_data(self):
        show_version_out = self.show('show version')
        try:
            version_data = get_structured_data(
                'cisco_ios_show_version.template', show_version_out)[0]
            return version_data
        except IndexError:
            return {}

    def rollback(self, rollback_to):
        try:
            self.show('configure replace flash:%s force' % rollback_to)
        except CommandError:
            raise RollbackError('Rollback unsuccessful. %s may not exist.' %
                                rollback_to)

    def checkpoint(self, checkpoint_file):
        self.save(filename=checkpoint_file)

    @property
    def facts(self):
        if hasattr(self, '_facts'):
            return self._facts

        facts = {}
        facts['vendor'] = self.vendor

        version_data = self._raw_version_data()
        show_version_facts = convert_dict_by_key(version_data,
                                                 ios_key_maps.BASIC_FACTS_KM)

        facts.update(show_version_facts)

        uptime_full_string = version_data['uptime']
        facts['uptime'] = self._uptime_to_seconds(uptime_full_string)
        facts['uptime_string'] = self._uptime_to_string(uptime_full_string)

        facts['fqdn'] = 'N/A'
        facts['interfaces'] = list(x['intf']
                                   for x in self._interfaces_detailed_list())

        if show_version_facts['model'].startswith('WS'):
            facts['vlans'] = list(str(x['vlan_id']) for x in self._show_vlan())
        else:
            facts['vlans'] = []

        # ios-specific facts
        ios_facts = facts[IOS_SSH_DEVICE_TYPE] = {}
        ios_facts['config_register'] = version_data['config_register']

        self._facts = facts
        return facts

    @property
    def running_config(self):
        return self.show('show running-config', expect=True)

    @property
    def startup_config(self):
        return self.show('show startup-config')
Ejemplo n.º 5
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.º 6
0
def main():
    """

    The ios_show_lab.py script is a discovery script which takes in a list of ip addresses and a project name as mandatory
    command line arguments and attempts to log in to one or more devices in the list of ips and extract and save the
    output of a set of show commands.
    Both the default login credentials and list of show commands can be overriden via optional command line
    arguments.
    The script also provides a "ping only" option to test reachability only.

    """

    ip_filename = arguments.ip_file.strip()

    # Set project directory to 'logs' unless an optional directory was given
    if arguments.project_dir:
        project = arguments.project_dir
    else:
        project = 'logs'

    if arguments.device_class:
        device_cls = arguments.device_class.strip()
    else:
        # Default device class for Netmiko
        device_cls = 'cisco_ios'

    ips = []
    ips = load_txt_file(ip_filename)

    total_devices = len(ips)
    # Track devices which fail login or pings
    missing_devices = []
    # Track devices which were successfully accessed
    devices_verified = 0

    # Create Directory for show output based on the Project Name
    path = os.path.join("./", project.strip())
    # print path
    if not os.path.exists(path):
        os.makedirs(path)
        print(f"Created directory: {path}")

    # Create logfile for the discovery run in same directory as the resulting show commands
    # logfilename = project + "-logfile.log"
    # logfilename = os.path.join(path, logfilename)

    if total_devices > 1:
        heading = f"##### Executing show commands for discovery project {project} for {str(total_devices)} devices! #####"
    else:
        heading = f"##### Executing show commands for discovery project {project} for {str(total_devices)} device! #####"

    print("#" * len(heading))
    print(heading)
    print("#" * len(heading))

    print(f"Device IP(s) in project {project}:")
    for i in ips:
        print(f"\t{i}")
    print("--------------------------")
    print(f"Total devices: {str(len(ips))}")
    print("#" * len(heading))
    print("\n")

    ## Default Credentials
    # Default list of credentials in format username, user password, enable password
    credentials = ['cisco, cisco, cisco']

    ## Load Credentials if -c or --creds option was used
    if arguments.creds:
        # Override default credentials as a new credential file with one or more sets of credentials was provided
        cred_filename = arguments.creds
        credentials = load_txt_file(cred_filename)

    ##### SHOW COMMANDS
    commands = []

    ## Load custom show commands if -c or --show option was used
    if arguments.show:
        # Override default list of show commands as a new file with one or more show commands was provided
        show_filename = arguments.show
        custom_showcmds = load_txt_file(show_filename)

        # first command to send is an end to get back to the main prompt
        commands = custom_showcmds

    else:
        # DEFAULT SHOW COMMANDS
        commands = [
            "show version",
        ]

    # if not arguments.pingonly:
    #     print("Sending " + str(len(commands)) + " show commands:")
    #     for x in range(0, len(commands)):
    #         print("\t" + commands[x])

    # For each IP in the ip address file, attempt to ping, attempt to log in, attempt to enter enable mode and
    # execute and save show command output
    for mgmt_ip in ips:

        login_success = False
        enable_success = False
        output = ''
        hostname = "dev_" + mgmt_ip

        # If Ping is successful attempt to log in and if that is successful attempt to enter enable mode and
        # execute list of show commands
        device_pings = ping_device(mgmt_ip)

        if device_pings:
            print(f"Device {mgmt_ip} Responds to Pings!\n")

            # If the -i or --icmppingonly option was provided when the script was called, then only execute the ping code.
            if arguments.icmppingonly:
                # Keep a count of the devices that are pingable
                devices_verified += 1
                # Skip everything else as the icmp ping only option was given
                continue

            if len(credentials) > 1:
                print(
                    "**** Attempting multiple credentials to access device...."
                )

            try_telnet = False
            # Credential Loop
            for line in credentials:

                lineitem = line.split(',')
                uname = lineitem[0].strip()
                upwd = lineitem[1].strip()
                epwd = lineitem[2].strip()

                if not try_telnet:

                    print(
                        f"\t**** Attempting user credentials for {uname} with SSH."
                    )

                    try:
                        dev_conn = ConnectHandler(device_type=device_cls,
                                                  ip=mgmt_ip,
                                                  username=uname,
                                                  password=upwd,
                                                  secret=epwd)
                        login_success = True

                    except NetMikoAuthenticationException:
                        print(
                            f"\tNetMikoAuthenticationException: Device failed SSH Authentication with username {uname}"
                        )
                        missing_devices = missing_device_log(
                            missing_devices, mgmt_ip, 'Failed Authentication')
                        login_success = False
                        # continue

                    except (EOFError, SSHException, NetMikoTimeoutException):
                        print('\tSSH is not enabled for this device.')
                        missing_devices = missing_device_log(
                            missing_devices, mgmt_ip, 'Failed SSH')
                        login_success = False
                        try_telnet = True
                        # continue

                    except Exception as e:
                        print("\tGeneral Exception: ERROR!:" +
                              str(sys.exc_info()[0]) + "==>" +
                              str(sys.exc_info()[1]))
                        print(str(e))
                        missing_devices = missing_device_log(
                            missing_devices, mgmt_ip, 'General Exception')
                        login_success = False
                        # continue

                    if login_success:
                        print(
                            "\t**** SSH Login Succeeded! Will not attempt login with any other credentials."
                        )
                        # Break out of credential loop
                        break
                    else:
                        print("\t**** SSH Login Failed!")
                        # continue

                # Try Telnet
                if try_telnet:
                    print("\t**** Attempting user credentials for " + uname +
                          " with Telnet.")

                    try:
                        dev_conn = ConnectHandler(
                            device_type='cisco_ios_telnet',
                            ip=mgmt_ip,
                            username=uname,
                            password=upwd,
                            secret=epwd)
                        login_success = True

                    except NetMikoAuthenticationException:
                        print(
                            f"\tNetMikoAuthenticationException: Device failed SSH Authentication with username {uname}"
                        )
                        missing_devices = missing_device_log(
                            missing_devices, mgmt_ip, 'Failed Authentication')
                        login_success = False
                        continue

                    except Exception as e:
                        print("\tGeneral Exception: ERROR!:" +
                              str(sys.exc_info()[0]) + "==>" +
                              str(sys.exc_info()[1]))
                        print(str(e))
                        missing_devices = missing_device_log(
                            missing_devices, mgmt_ip, 'General Exception')
                        login_success = False
                        continue

                    if login_success:
                        print(
                            "\t**** Telnet Login Succeeded! Will not attempt login with any other credentials."
                        )
                        # Break out of credential loop
                        break
                    else:
                        print("\t**** Telnet Login Failed!")
                        continue

            if login_success:
                # Check to see if login has resulted in enable mode (i.e. priv level 15)
                is_enabled = dev_conn.check_enable_mode()

                if not is_enabled:
                    try:
                        dev_conn.enable()
                        enable_success = True
                    except Exception as e:
                        print(str(e))
                        print("\tCannot enter enter enable mode on device!")
                        missing_devices = missing_device_log(
                            missing_devices, mgmt_ip, 'failed enable')
                        enable_success = False
                        continue
                else:
                    print("\tDevice already in enabled mode!")
                    enable_success = True

            if enable_success:

                for cmd in commands:
                    output += dev_conn.send_command(cmd,
                                                    strip_prompt=False,
                                                    strip_command=False)
                dev_conn.exit_config_mode()
                dev_conn.disconnect()

                # output contains a stream of text vs individual lines
                # split into individual lies for further parsing
                # output_lines = re.split(r'[\n\r]+', output)

                # show_info = get_show_info(output_lines)
                #
                # if show_info['hostname']:
                #     hostname = show_info.pop('hostname')

                # print("Information for device: " + hostname)
                # for k, v in show_info.items():
                #     print("\t" + k +"\t\t-\t" + v)

                # Save output to file
                timestr = time.strftime("%Y%m%d-%H%M%S")

                log_filename = hostname + "-" + timestr + ".txt"
                log_filename = os.path.join(path, log_filename)

                log_file = open(log_filename, 'w')
                log_file.write("!#Output file for device " + hostname + "\n")
                log_file.write("!#Commands executed on " + timestr + "\n\r")
                log_file.write("!\n")
                log_file.write(output)
                log_file.close()
                devices_verified += 1
                print("\nOutput results saved in: " + log_filename + "\n\n")

        else:
            # Device does not PING
            print("Device is unreachable")
            missing_devices.append(mgmt_ip)

    # Totals Verification
    if arguments.icmppingonly:
        info = ("Total number of devices in IP list:\t\t" +
                str(total_devices) + "\n",
                "Total number of devices which responded to pings:\t" +
                str(devices_verified) + "\n")
    else:
        info = ("Total number of devices in IP list:\t\t" +
                str(total_devices) + "\n",
                "Total number of show command output files:\t" +
                str(devices_verified) + "\n")

    # Print Note on totals
    for note in info:
        print(note)
from netmiko import ConnectHandler
import getpass

password = getpass.getpass('Enter Arista1 Password:'******'device_type': 'arista_eos',
    'ip': '10.1.1.3',
    'username': '******',
    'password': password,
    'port': 22,
    'secret': password,
    'verbose': True
}

connection = ConnectHandler(** arista_device)
    
if not connection.check_enable_mode():
    connection.enable()

output = connection.send_command('show interface status')

print(output)

connection.disconnect()


    
Ejemplo n.º 8
0
def login_into_device(remote_host, username, password, enablepassword, iter, telnet_port=23, ssh_port=22 ):
    device = {}
    net_connect = {}
    socketM = {}
    dev_type = ''
    socketM = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    CONNECT_FLAG = 1
    CONNECT_SUCCESS = 0
    if socketM.connect_ex((remote_host, telnet_port)) == 0:
        print('Connection established via TELNET')
        # device = get_device('cisco_ios_telnet', remote_host, input("Enter username: "******"Enter password: "******"Enter enable password: "******"Could not connect to the node with TELNET \n Trying with SSH\n")
            CONNECT_FLAG = 1
            device.clear()
            socketM.close()
            socketM = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    if (CONNECT_FLAG == 1) and (socketM.connect_ex((remote_host, ssh_port)) == 0):
        print('Connection established via SSH')
        # device = get_device('cisco_ios_ssh', remote_host, input("Enter username: "******"Enter password: "******"Enter enable password: "******"Problem Occured with SSH Login")
            CONNECT_SUCCESS = 0

    if CONNECT_SUCCESS == 0:
        print('Unable to connect')
        socketM.close()
        device.clear()
        # exit(-1)
        # net_connect.disconnect()
    if CONNECT_SUCCESS == 1:
        # net_connect.set_terminal_width(0)
        if (net_connect.check_enable_mode() == False):
            try:
                net_connect.enable()
                if (net_connect.check_enable_mode() == True):
                    print("############### Credential verified for device {} ##################".format(iter + 1))
            except Exception as e:
                print(str(e))
                print("----Error in Enable Password---Try Again")
                net_connect = {}

        # print("############### Credential verified for device {} ##################".format(i + 1))

    return net_connect, dev_type
Ejemplo n.º 9
0
class CiscoIOS:
    def __init__(self, device_param):
        if 'hostname' in device_param:
            del (device_param['hostname'])
        self.device_param = device_param
        try:
            self.ssh = ConnectHandler(**device_param)
        except NetMikoAuthenticationException:
            raise NetMikoAuthenticationException
        except NetMikoTimeoutException:
            raise NetMikoTimeoutException

        if not self.ssh.check_enable_mode() and self.device_param['secret']:
            self.ssh.enable()

    def enable_scp(self):
        return self.ssh.send_config_set(['ip scp server enable'])

    def disable_scp(self):
        return self.ssh.send_config_set(['ip scp server enable'])

    def load_file(self, file, dst_file=None):
        if not dst_file:
            dst_file = file
        scp_status = self.ssh.send_command(
            'show running-config | i "ip scp server enable"')
        if not scp_status:
            self.enable_scp()
        scp = SCPConn(self.ssh)
        scp.scp_transfer_file(file, dst_file)
        scp.close()
        if not scp_status:
            self.disable_scp()

    '''
    #show switch
    Switch/Stack Mac Address : e089.9d50.7000
                                               H/W   Current
    Switch#  Role   Mac Address     Priority Version  State 
    ----------------------------------------------------------
    *1       Master e089.9d50.7000     15     1       Ready               
     2       Member 1ce8.5d68.7b00     14     1       Ready               
     3       Member 1ce8.5d68.3980     13     1       Ready               
     4       Member 1ce8.5d8a.cc80     12     1       Ready               
    '''

    def get_switches(self):
        p = re.compile(
            r"""              
                        (\s|\*)
                        (?P<switch>\d)
                        \s+                          
                        (?P<role>Member|Master)    
                        \s+                       
                        (?P<mac>[a-z0-9]{4}\.[a-z0-9]{4}\.[a-z0-9]{4})                
                        \s+                           
                        (?P<prior>\d{1,2})
                        \s+
                        (?P<version>\d+)
                        \s+
                        (?P<state>Ready|.*?)
                        \s+
                        """, re.VERBOSE)
        ret = self.ssh.send_command('show switch', delay_factor=5)
        for line in ret.splitlines()[3:]:
            switch = {}
            if p.search(line):
                switch['switch'] = p.search(line).group('switch')
                switch['role'] = p.search(line).group('role')
                switch['mac'] = p.search(line).group('mac')
                switch['prior'] = p.search(line).group('prior')
                switch['version'] = p.search(line).group('version')
                switch['state'] = p.search(line).group('state')
                yield switch

    '''
    Flash to flash copy function. Don't use '/' in src, dst path after colon symbol:
    #copy flash:c2960s-universalk9-mz.150-2.SE11.bin flash2:c2960s-universalk9-mz.150-2.SE11.bin
    Destination filename [c2960s-universalk9-mz.150-2.SE11.bin]? 
    Copy in progress...CCCCCCCC
    '''

    def f2f_copy(self, src, dst):
        ret = self.ssh.send_command_timing('copy {0} {1}'.format(src, dst))
        if 'Destination filename [{0}]?'.format(dst[dst.find(':') +
                                                    1:]) in ret:
            ret += self.ssh.send_command_timing('')
        return ret

    '''
    #show flash3: | i bytes total
    122185728 bytes total (30591488 bytes free)
    '''

    def flash_size(self, flash='flash:'):
        ret = self.ssh.send_command('show {0} | i bytes total'.format(flash))
        return int(ret[:ret.find(' ')])

    def flash_free(self, flash='flash:'):
        ret = self.ssh.send_command('show {0} | i bytes total'.format(flash))
        return int(ret[ret.find('(') + 1:ret.rfind(' bytes free')])

    def file_exist(self, file, flash='flash:'):
        if self.ssh.send_command('show {0} | i {1}'.format(flash, file)):
            return True
        return False

    def set_image(self, image):
        return self.ssh.send_config_set(
            ['boot system switch all flash:/{0}'.format(image)])

    def reload(self, save=False):
        if save:
            self.write()
        ret = self.ssh.send_command_timing('reload')
        if 'Proceed with reload? [confirm]' in ret:
            ret += self.ssh.send_command_timing('')
        return ret

    def write(self):
        return self.ssh.send_command('write memory')
Ejemplo n.º 10
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.º 11
0

for host in ip_add_file:
    host = host.strip()
    print(host)
    device = ConnectHandler(device_type=platform, ip=host, username=username, password=password, secret=password)
    output = device.send_command('terminal length 0')
    print('##############################################################\n')
    print('...................COMMAND SHOW RUN OUTPUT......................\n')
    output = device.send_command('sh version')
    print(output)
    print('##############################################################\n')
    print('...................ENABLE......................\n')
    output = device.send_command('sh switch')
    print(2)
    print(output)
    print(device.enable(cmd='enable', pattern="ssword"))
    print(3)
    print('##############################################################\n')
    print('...................WRITE......................\n')

    print (device.check_enable_mode())
    print(device.is_alive())

    print(device.send_command('sho run inter vla 99', expect_string='exit', delay_factor=1, max_loops=500, auto_find_prompt=True, strip_prompt=True, strip_command=True, normalize=True, use_textfsm=False, use_genie=False))
    #expected string seem important on Dell
    
    print('##############################################################\n')

#fd.close()
Ejemplo n.º 12
0
with open('routerlist') as f:
    content = f.readlines()

content = [x.strip() for x in content]
host_list = content
for host in host_list:
    print "Connecting to device %s with cerdentials of %s" % (host, user_name)
    cisco = {
        'device_type': 'cisco_ios',
        'ip': host,
        'username': user_name,
        'password': pwd
    }
    ssh_conn = ConnectHandler(**cisco)
    if ssh_conn.check_enable_mode() == True:
        print 'logged into the device and we are in enable prompt !'
    else:  #
        print 'Ops !! something wrong with the password of %s, pls try again !!' % username
    print "preparing the details for the audit"
    #    sh_cmd_45 = ssh_conn.send_command(cmd_45)
    #    print "****************************"
    #    print host
    #    if not sh_cmd_45:
    #        print "not ASR router, can you pls crosscheck again !!!"
    #    else:
    sh_mem_output = ssh_conn.send_command(show_cmd)

    sh_mem_output = ssh_conn.send_command(show_cmd)
    #        sh_mem_outputlines = sh_mem_output.splitlines()[4]
    #        sh_mem_outputcontent = sh_mem_outputlines.split()[0] +" free_space " + sh_mem_outputlines.split()[4]
Ejemplo n.º 13
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.º 14
0
def ccegate():

    with open('C:\\python39\\gatewayaudit012022v2.txt', 'w') as f:

        f.write('This is the start of the Gateway Audit \n')
        f.write(" \n")
        f.write('The report started at: ' + (str(start_time)))
        f.write(" \n")

        try:
            for a_device in gws:
                net_connect = ConnectHandler(**a_device)
                print("\n\n>>>>>>>>> Device {0} <<<<<<<<<".format(
                    a_device['ip']))
                f.write("\n\n>>>>>>>>> Device {0} <<<<<<<<<".format(
                    a_device['ip']))
                f.write("\n")
                output = net_connect.send_command('enable')
                output = net_connect.check_enable_mode()
                print('Is the gateway in enable mode: ' + (str(output)))
                f.write("Is the gateway in enable mode: " + (str(output)))
                f.write(" \n")
                output = net_connect.find_prompt()
                print('The gateway prompt: ' + (str(output)))
                f.write("The gateway prompt " + (str(output)))
                f.write(" \n")
                print()
                output = net_connect.send_command('terminal length 0')
                f.write(output)
                f.write("\n \n")
                f.write("This is a list of wav files found in flash:")
                f.write("\n")
                output = net_connect.send_command("sh flash: | i wav")
                f.write(output)
                f.write("\n")
                if len(output) == 0:
                    print('The WAV FILES are missing')
                    f.write("The WAV files are missing")
                f.write("\n")
                f.write('This is a list of tcl files located in flash:')
                f.write("\n")
                output = net_connect.send_command('sh flash: | i tcl')
                f.write(output)
                if len(output) == 0:
                    f.write('The TCL FILES are missing')
                f.write("\n")
                print()
                print('The script has started, please be patient.')
                print()
                f.write('This is a list of bin files located in flash:')
                f.write("\n \n")
                output = net_connect.send_command('sh flash: | i bin')
                f.write(output)
                if len(output) == 0:
                    f.write('The BIN FILES are missing')
                time.sleep(1)
                f.write("\n \n")
                f.write('This is a list of vxml files located in flash:')
                f.write("\n")
                output = net_connect.send_command('sh flash: | i vxml ')
                if len(output) == 0:
                    f.write('The VXML FILES are missing')
                time.sleep(1)
                f.write(output)
                f.write("\n \n")
                f.write('This is a list of the CCB files located in flash:')
                f.write("\n")
                output = net_connect.send_command('sh flash: | i ccb')
                if len(output) == 0:
                    f.write('The CCB FILES are missing')
                time.sleep(1)
                f.write(output)
                time.sleep(1)
                f.write("\n \n")
                f.write('This is the version of the gateway:')
                f.write("\n")
                output = net_connect.send_command("sh version | inc Version")
                f.write(output)
                f.write("\n \n")
                f.write('This checks if all applications loaded correctly')
                f.write("\n")
                output = net_connect.send_command("show call appl voice sum")
                f.write(output)
                f.write("\n")
                f.write('This shows the version of the tcl file:')
                f.write("\n")
                output = net_connect.send_command(
                    'more handoff.tcl | i Script ')
                time.sleep(.5)
                if len(output) == 0:
                    f.write('The HandOff file is missing')
                f.write(output)
                f.write("\n")
                output = net_connect.send_command(
                    'more bootstrap.tcl | i Script ')
                time.sleep(.5)
                if len(output) == 0:
                    f.write('The bootstrap file is missing')
                f.write(output)
                f.write("\n")
                output = net_connect.send_command(
                    'more cvp_ccb_dial.tcl | i Script ')
                time.sleep(.5)
                if len(output) == 0:
                    f.write('The cvp-ccb-dial file is missing')
                f.write(output)
                f.write("\n")
                output = net_connect.send_command(
                    'more cvp_ccb_poll.tcl | i Script ')
                time.sleep(.5)
                if len(output) == 0:
                    f.write('The cvp-ccb-poll file is missing')
                f.write(output)
                f.write("\n")
                print()
                print("The Script is still running")
                print()
                output = net_connect.send_command(
                    'more cvp_ccb_vxml.tcl | i Script ')
                time.sleep(.5)
                if len(output) == 0:
                    f.write('The svp-ccb-vxml file is missing.')
                f.write(output)
                f.write("\n")
                output = net_connect.send_command(
                    'more cvperror.tcl | i Script ')
                time.sleep(.5)
                if len(output) == 0:
                    f.write('The cvperror file is missing')
                f.write(output)
                f.write("\n")
                output = net_connect.send_command(
                    'more CVPSelfService.tcl | i Script')
                time.sleep(.5)
                if len(output) == 0:
                    f.write('The CVPSelfService file is missing')
                f.write(output)
                f.write("\n")
                output = net_connect.send_command(
                    'more ringtone.tcl | i Script')
                #maw
                time.sleep(.5)
                if len(output) == 0:
                    f.write('The ringtone file is missing')
                f.write(output)
                f.write("\n")
                output = net_connect.send_command(
                    'more survivability.tcl | i Script')
                time.sleep(.5)
                if len(output) == 0:
                    f.write('The Survivability file is missing')
                f.write(output)
                f.write("\n \n")
                output = net_connect.send_command('show run | s dial-peer')
                f.write('Here is the list of dial peers on the gateway:')
                f.write("\n")
                f.write(output)
                f.write("\n \n")
                f.write('Here is a status of the dial-peers')
                f.write("\n")
                output = net_connect.send_command('show dial-peer voice summ')
                f.write(output)
                f.write("\n \n")
                f.write('Here is a status of the voice ports')
                f.write("\n")
                output = net_connect.send_command('show voice port summ')
                if len(output) == 0:
                    f.write('No VOICE PORTs are configured on this gateway')
                f.write(output)
                f.write("\n \n")
                f.write('Here is a status of the http cache')
                f.write("\n")
                output = net_connect.send_command('show http cl cache')
                f.write(output)
                f.write("\n \n")
                f.write(
                    'Check http client stats for possible errors or timeouts')
                f.write("\n")
                f.write(
                    'If so, could be device located in network between HTTP server and HTTP client'
                )
                f.write("\n")
                output = net_connect.send_command('show http cl stat')
                f.write(output)
                f.write("\n \n")
                print("Script is still running")
                f.write(
                    'Best practice for CVP has bind commands under voice service voip'
                )
                f.write("\n")
                output = net_connect.send_command('show run | inc bind')
                if len(output) == 0:
                    f.write('The BIND command is missing')
                f.write(output)
                f.write("\n \n")
                f.write('Best practice for CVP with a sip proxy')
                f.write("\n")
                output = net_connect.send_command('show run | inc sip-server')
                f.write(output)
                f.write("\n \n")
                f.write(
                    'Best practice for CVP - has mediaserver and mediaserverbackup'
                )
                f.write("\n")
                # if blank how to point this out - 11/6 found 1 solution
                output = net_connect.send_command('show run | inc mediaserver')
                if len(output) == 0:
                    f.write('The IP HOST command is missing')
                f.write(output)
                f.write("\n \n")
                f.write(
                    'Best practice for CVP with Enhanced UUI Feature turned on'
                )
                f.write("\n")
                output = net_connect.send_command(
                    'show run | inc signaling forward unconditional')
                if len(output) == 0:
                    f.write('The UUI Feature is not Used')
                f.write(output)
                f.write("\n \n")
                f.write('Best practice for Voice Service Voip - trusted IP')
                f.write("\n")
                output = net_connect.send_command(
                    'show run | i trusted authenticate')
                if len(output) == 0:
                    f.write('The Trusted Authenticate command is missing')
                f.write(output)
                f.write("\n \n")
                f.write("\n")
                f.write('Best practice for CVP with a gateway - no logging')
                f.write("\n")
                output = net_connect.send_command('show run | inc no logging')
                if len(output) == 0:
                    f.write('The no logging command is missing')
                f.write(output)
                f.write("\n \n")
                time.sleep(.5)
                f.write('Best practice for CVP with a gateway - ip cef')
                f.write("\n")
                output = net_connect.send_command('show run | inc ip cef')
                if len(output) == 0:
                    f.write('The IP CEF command is missing')
                f.write(output)
                f.write("\n \n")
                time.sleep(.5)
                f.write('Best practice for CVP with a gateway - voice rtp')
                f.write("\n")
                output = net_connect.send_command('show run | inc voice rtp')
                if len(output) == 0:
                    f.write('The VOICE RTP send-recv command is missing')
                f.write(output)
                f.write("\n \n")
                time.sleep(.5)
                f.write(
                    'Best practice for CVP with a gateway - signaling forward')
                f.write("\n")
                output = net_connect.send_command(
                    'show run | inc signaling forward')
                if len(output) == 0:
                    f.write('The SIGNALING FORWARD command is missing')
                f.write(output)
                f.write("\n \n")
                f.write('Best practice for CVP with a gateway - min-se')
                f.write("\n")
                output = net_connect.send_command('show run | inc min-se')
                if len(output) == 0:
                    f.write('The MIN SE command is missing')
                f.write(output)
                f.write("\n \n")
                f.write(
                    'Best practice for CVP with a gateway - timer receive-rtcp'
                )
                f.write("\n")
                output = net_connect.send_command(
                    'show run | inc timer receive-rtcp')
                if len(output) == 0:
                    f.write('The RECEIVE RTCP command is missing')
                f.write(output)
                f.write("\n \n")
                f.write('Best practice for CVP with a gateway - ip rtcp')
                f.write("\n")
                output = net_connect.send_command('show run | inc ip rtcp')
                if len(output) == 0:
                    f.write('The IP RTCP command is missing')
                f.write(output)
                f.write("\n \n")
                time.sleep(.5)
                f.write('Best practice for CVP with a gateway - reason-header')
                f.write("\n")
                output = net_connect.send_command(
                    'show run | inc reason-header')
                if len(output) == 0:
                    f.write('The REASON HEADER OVERRIDE command is missing')
                f.write(output)
                f.write("\n \n")
                f.write(
                    'Best practice for CVP with a vxml gateway - 4 ivr commands'
                )
                f.write("\n")
                output = net_connect.send_command('show run | inc ivr')
                if len(output) == 0:
                    f.write('The IVR commands are missing')
                f.write(output)
                f.write("\n \n")
                f.write(
                    'Best practice for CVP with a vxml gateway - 3 mrcp commands'
                )
                f.write("\n")
                output = net_connect.send_command('show run | inc mrcp')
                if len(output) == 0:
                    f.write('The MRCP commands are missing')
                f.write(output)
                f.write("\n \n")
                time.sleep(.5)
                print("The Script is still running")
                f.write(
                    'Best practice for CVP with a vxml gateway - 2 rtsp commands'
                )
                f.write("\n")
                output = net_connect.send_command('show run | inc rtsp')
                if len(output) == 0:
                    f.write('The RTSP commands are missing')
                f.write(output)
                f.write("\n \n")
                f.write(
                    'Best practice for CVP with a vxml gateway - 1 vxml tree')
                f.write("\n")
                output = net_connect.send_command('show run | inc vxml tree')
                if len(output) == 0:
                    f.write('The VXML TREE command is missing')
                f.write(output)
                f.write("\n \n")
                time.sleep(.5)
                f.write(
                    'Best practice for CVP with a vxml gateway - 5 http client commands'
                )
                f.write("\n")
                output = net_connect.send_command('show run | inc http client')
                if len(output) == 0:
                    f.write('The HTTP CLIENT commands are missing')
                f.write(output)
                f.write(' \n \n')
                f.write(
                    'Best practice for CVP from OAMP template gw - ip-source route'
                )
                f.write("\n")
                output = net_connect.send_command(
                    'show run | inc ip-source route')
                if len(output) == 0:
                    f.write('The IP SOURCE ROUTE command is missing')
                f.write(output)
                f.write(' \n \n')
                time.sleep(.5)
                f.write(
                    'Best practice for CVP from OAMP template gw - header-passing'
                )
                f.write("\n")
                output = net_connect.send_command(
                    'show run | inc header-passing')
                if len(output) == 0:
                    f.write('The HEADER PASSING command is missing')
                f.write(output)
                f.write(' \n \n')
                time.sleep(.5)
                f.write(
                    'Best practice for CVP from OAMP template gw - codec preference'
                )
                f.write("\n")
                output = net_connect.send_command(
                    'show run | inc codec preference')
                f.write(output)
                f.write(' \n \n')
                f.write('Best practice for CVP from OAMP template gw - sip-ua')
                f.write("\n")
                output = net_connect.send_command('show run | inc sip-ua')
                f.write(output)
                f.write(' \n \n')
                f.write(
                    'Best practice for CVP from OAMP template gw - retry invite 2'
                )
                f.write("\n")
                output = net_connect.send_command(
                    'show run | inc retry invite 2')
                if len(output) == 0:
                    f.write('The RETRY INVITE command is missing')
                f.write(output)
                f.write(' \n \n')
                f.write(
                    'Best practice for CVP from OAMP template gw - retry bye 2'
                )
                f.write("\n")
                output = net_connect.send_command('show run | inc retry bye 2')
                if len(output) == 0:
                    f.write('The RETRY BYE command is missing')
                f.write(output)
                f.write(' \n \n')
                f.write(
                    'Best practice for CVP from OAMP template gw - timers expires '
                )
                f.write("\n")
                output = net_connect.send_command(
                    'show run | inc timers expires')
                if len(output) == 0:
                    f.write('The TIMERS EXPIRES command is missing')
                f.write(output)
                f.write(' \n \n')
                f.write(
                    'Best practice for CVP from OAMP template vxml gw - ip routing '
                )
                f.write("\n")
                output = net_connect.send_command('show run | inc ip routing')
                if len(output) == 0:
                    f.write('The IP ROUTING command is missing')
                f.write(output)
                f.write(' \n \n')
                f.write(
                    'Best practice for CVP from OAMP template vxml gw - asr-server '
                )
                f.write("\n")
                output = net_connect.send_command('show run | inc asr-server')
                if len(output) == 0:
                    f.write('The ASR SERVER command is missing')
                f.write(output)
                f.write(' \n \n')
                f.write(
                    'Best practice for CVP from OAMP template vxml gw - tts-server '
                )
                f.write("\n")
                print("The Report is almost Finished.")
                output = net_connect.send_command('show run | inc tts-server')
                if len(output) == 0:
                    f.write('The TTS SERVER command is missing')
                f.write(output)
                f.write("\n \n")
                f.write("\n")
                f.write(
                    'Best practice for CVP from OAMP template vxml gw - vxml audioerror '
                )
                f.write("\n")
                output = net_connect.send_command(
                    'show run | inc vxml audioerror')
                if len(output) == 0:
                    f.write('The VXML AUDIOERROR command is missing')
                f.write(output)
                f.write("\n")
                f.write(
                    'Best practice for CVP from OAMP template vxml gw - vxml version 2 '
                )
                f.write("\n")
                output = net_connect.send_command(
                    'show run | inc vxml version')
                if len(output) == 0:
                    f.write('The VXML VERSION command is missing')
                f.write(output)
                f.write("\n")
                f.write('New Commands can go here  ')
                f.write("\n")
                #un comment out the next line and replace the show run command with a new command.
                #output = net_connect.send_command('show run | inc  ')
                f.write(output)
                f.write("\n")
                f.write('Check for network based recording on gateway to CUCM')
                f.write("\n")
                output = net_connect.send_command('show run | inc uc wsapi')
                if len(output) == 0:
                    f.write('The NETWORK BASED RECORDING command is missing')
                f.write(output)
                print()
                f.write("\n")
                f.write('Check for NTP Servers')
                f.write("\n")
                output = net_connect.send_command('show run | inc ntp server')
                if len(output) == 0:
                    f.write('The seems to be no NTP Servers configured')
                f.write(output)
                f.write('Check SIP Status')
                f.write("\n")
                output = net_connect.send_command('show sip status')
                f.write(output)
                f.write("\n")
                f.write('Check CPU')
                f.write("\n")
                output = net_connect.send_command('show process cpu history')
                f.write(output)
                f.write("\n")
                #MAW
                f.write("\n \n")
                print()
                print(">>>>>>>>> End <<<<<<<<<")
                f.write(">>>>>>>>> End <<<<<<<<<")
        except netmiko.ssh_exception.NetMikoTimeoutException as n:
            print(n)
            print('Is your VPN connected?')
            f.write(' \n')
            f.write("Is the VPN connected, I see an error.")
            f.write(" \n")
        except netmiko.ssh_exception.NetmikoAuthenticationException as n:
            print(n)
            print('Invalid username or password.')
            f.write(' \n')
            f.write("Invalid Username or Password.")
            f.write(" \n")
        except OSError as e:
            print(e)
Ejemplo n.º 15
0
def run_script(host_ip, vendor, cmds):
    device = {
        "device_type":
        vendor,
        "ip":
        host_ip,
        "username":
        uname,
        "password":
        passwd,
        "session_log":
        str(date) + "_" + str(vendor) + "_" + (str(host_ip)).strip() + "_" +
        str(hour) + ".txt",
        "secret":
        secret
    }

    try:
        net_connect = ConnectHandler(**device)  #connect to the device via ssh

        print("\nConnected to host:", vendor, host_ip)

    except:
        print("\nConnection lost to host:", vendor, host_ip,
              "Please, check your credentials !!")
        quit()

    try:
        if not net_connect.check_enable_mode():

            connection.enable()
            print("\nAcessing privileged mode")

    except ValueError:
        print("Wrong enable password on device: ", vendor, host_ip)
        quit()

    if args.command:
        output = net_connect.send_command_timing(cmds, delay_factor=2)
        print('\n====>', vendor, host_ip, cmds, '\n')
        print(output)
        print('\n--- Elapsed time=', time() - starting_time)
        sleep(2)

    else:
        for commands in cmds:
            if args.show:
                output = net_connect.send_command_timing(commands,
                                                         delay_factor=2)
                print('\n====>', vendor, host_ip, commands, '\n')
                print(output)
                print('\n--- Elapsed time=', time() - starting_time)
                sleep(2)

            elif args.conf:
                output = net_connect.send_config_set(
                    commands
                )  # If you want to send configuration commands rather than "show commands", please uncomment this line
                print('\n====>', vendor, host_ip, commands, '\n')
                print(output)
                print('\n--- Elapsed time=', time() - starting_time)
                sleep(2)
Ejemplo n.º 16
0
class CiscoIOS:
    """Class for cisco ios device"""
    def __init__(self, device_param):
        """constructor

        :param device_param: dict with option for netmiko

        """
        del (device_param['hostname'])  # delete external for netmiko key
        self.device_param = device_param
        try:
            self.ssh = ConnectHandler(**device_param)
        except NetMikoAuthenticationException:
            raise
        except NetMikoTimeoutException:
            raise

        if not self.ssh.check_enable_mode() and \
                self.device_param['secret']:
            self.ssh.enable()

    def load_ssh_key(self, id_rsa=None, user=None):
        """load id_rsa.pub key on cisco device

        :param id_rsa: path for ket, default use: .ssh/id_rsa.pub
        :param user: username, default use: running username

        """
        if not id_rsa:
            id_rsa = expanduser('~') + '/.ssh/id_rsa.pub'
        if not user:
            user = getpass.getuser()
        pubkey = open(id_rsa, 'r').read()
        pubkey = textwrap.wrap(pubkey, 80)

        commands = ['ip ssh pubkey-chain', 'username ' + user, 'key-string'
                    ] + pubkey + ['exit']
        ret = self.ssh.send_config_set(commands)
        print(ret)
        if ret.find('Invalid input detected') != -1:
            ret = 'invalid input error'
        return ret

    def del_ssh_key(self, user):
        commands = ['ip ssh pubkey-chain', 'no username ' + user, 'exit']
        return self.ssh.send_config_set(commands)

    def get_all_interfaces(self, search_filter=None):
        if search_filter:
            command = 'sh int status |' + search_filter
        else:
            command = 'sh int status'
        p = re.compile(
            r"""
                        (?P<name>[GFT]\D+\d/\d/\d+|[GFT]\D+\d/\d+)
                        (?P<description>.*)
                        (?P<status>connected|notconnect|disabled|err-disabled)
                        \s*
                        (?P<vlan>\d+|trunk)
                        """, re.VERBOSE)
        ports = []
        for line in self.ssh.send_command(command).split('\n'):

            interface = {}
            if p.search(line):
                interface['name'] = p.search(line).group('name')
                interface['description'] = p.search(line).group('description')
                interface['status'] = p.search(line).group('status')
                interface['vlan'] = p.search(line).group('vlan')
                ports.append(interface)
        return ports

    def get_all_acc_int(self):
        for c in self.get_all_interfaces():
            if c['vlan'] != 'trunk':
                yield c

    def get_all_vlans(self):
        vlans = []
        for line in self.ssh.send_command(
                'show vlan brief | i ^[0-9].*active').split('\n'):
            vlan = {}
            vlan['vlan'] = line[:line.find(' ')]
            vlan['name'] = line[line.find(' '):line.find(' active')]
            vlans.append(vlan)
        return vlans

    def is_port_trunk(self, port):
        ret = False
        if (self.ssh.send_command('show interface status | i ' +
                                  port).find('trunk') != -1):
            ret = True
        return ret

    def is_port_access(self, port):
        ret = False
        if (self.ssh.send_command('show interface status | i ' +
                                  port).find('trunk') == -1):
            ret = True
        return ret

    def switch_access_vlan(self, port, vlan):
        commands = ['interface ' + port, 'switchport access vlan ' + vlan]
        return self.ssh.send_config_set(commands)

    def show_priv(self):
        ret = self.ssh.send_command('show privilege')
        return int(ret[ret.rfind(' '):])

    def find_port_by_mac(self, mac):
        """
        Find port by mac add on local switch

        :param mac: - mac add in format: aaaa.bbbb.cccc
        :return: - port name, if port exist and it only one
        """
        if not mac:
            return None
        ports = []
        for line in self.ssh.send_command('sh mac add | i ' + mac).split('\n'):
            port = line[line.rfind(' '):]
            port = port.strip()
            ports.append(port)
        if len(ports) == 1:
            return ports[0]
        else:
            return None

    def find_sw_by_port(self, port):
        """
        Find neighbors by local port name, if port in etherchannel, firs find one of physical interface
        WARNING: all device must have identical domain name!

        :param port: - local switch port name, may be Po interface!
        :return: - neighbors name or null if find error
        """
        if not port:
            return None

        if port.find('Po') != -1:
            # find any physical interface in portchannel
            # msk101-sw-root#sh etherchannel summary | i Po31
            # 31     Po31(SU)        LACP      Te1/2/3(P)     Te1/2/4(P)     Te2/2/3(P)
            # newport = Te2/2/3
            newport = self.ssh.send_command('show etherchannel summary | i ' +
                                            port)
            if newport:
                newport = newport.rstrip()
                port = newport[newport.rfind(' '):newport.rfind(
                    '(')]  # Te2/2/3(P) -> Te2/2/3
                port = port.strip()

        # Te2/2/3 -> Ten 2/2/3
        if port[0:2] == 'Te':
            port = 'Ten ' + port[2:]
        elif port[0:2] == 'Gi':
            port = 'Gig ' + port[2:]
        elif port[0:2] == 'Fa':
            port = 'Fas ' + port[2:]

        # find neighbour on physical interface: show cdp neighbors
        # Device ID        Local Intrfce     Holdtme    Capability  Platform  Port ID
        # AP881d.fcd5.cf2a Gig 4/0/47        168              R T   AIR-CAP36 Gig 0.1
        # agg-sw-1.medsigroup.ru
        #                  Ten 2/2/3         171             R S I  WS-C6503- Ten 1/2/1
        # agg-sw-1.medsigroup.ru
        #                  Ten 3/0/1         175             R S I  WS-C6503- Ten 1/2/3
        # ...
        # sw = agg-sw-1.medsigroup.ru
        p = re.compile(
            r"""
                        (?P<dev>^.*?\ +?)
                        (?P<port>[Ten|Gig|Fas]+\ [\d{1,2}/\d{1,2}/\d{1,2}|\d{1,2}/\d{1,2}]+\ )  # only Local Interface
                        """, re.VERBOSE)
        cdp = self.ssh.send_command('show cdp neighbors | begin Device ID')
        sw = None
        tmp = ''
        for line in cdp.split('\n'):
            if line.find('Local Intrfce') != -1:
                continue  # always discard first line
            if len(line.split(' ')) == 1:
                tmp = line  # long device name on first line
                continue
            if tmp:
                line = tmp + ' ' + line  # concat long device name with base string
                tmp = ''
            if p.search(line):
                prt = p.search(line).group('port')
                prt = prt.strip()
                if prt == port:
                    sw = p.search(line).group('dev')
                    break
        return sw

    def write_memory(self):
        return self.ssh.send_command('write me')
Ejemplo n.º 17
0
class IOSDevice(BaseDevice):
    def __init__(self, host, username, password, secret='', port=22, **kwargs):
        super(IOSDevice, self).__init__(host, username, password, vendor='cisco', device_type=IOS_SSH_DEVICE_TYPE)

        self.native = None

        self.host = host
        self.username = username
        self.password = password
        self.secret = secret
        self.port = int(port)
        self._connected = False
        self.open()

    def open(self):
        if self._connected:
            try:
                self.native.find_prompt()
            except:
                self._connected = False

        if not self._connected:
            self.native = ConnectHandler(device_type='cisco_ios',
                                         ip=self.host,
                                         username=self.username,
                                         password=self.password,
                                         port=self.port,
                                         secret=self.secret,
                                         verbose=False)
            self._connected = True

    def close(self):
        if self._connected:
            self.native.disconnect()
            self._connected = False

    def _enter_config(self):
        self._enable()
        self.native.config_mode()

    def _enable(self):
        self.native.exit_config_mode()
        if not self.native.check_enable_mode():
            self.native.enable()

    def _send_command(self, command, expect=False, expect_string=''):
        if expect:
            if expect_string:
                response = self.native.send_command_expect(command, expect_string=expect_string)
            else:
                response = self.native.send_command_expect(command)
        else:
            response = self.native.send_command(command)

        if '% ' in response or 'Error:' in response:
            raise CommandError(command, response)

        return response

    def config(self, command):
        self._enter_config()
        self._send_command(command)
        self.native.exit_config_mode()

    def config_list(self, commands):
        self._enter_config()
        entered_commands = []
        for command in commands:
            entered_commands.append(command)
            try:
                self._send_command(command)
            except CommandError as e:
                raise CommandListError(
                    entered_commands, command, e.cli_error_msg)
        self.native.exit_config_mode()

    def show(self, command, expect=False, expect_string=''):
        self._enable()
        return self._send_command(command, expect=expect, expect_string=expect_string)

    def show_list(self, commands):
        self._enable()

        responses = []
        entered_commands = []
        for command in commands:
            entered_commands.append(command)
            try:
                responses.append(self._send_command(command))
            except CommandError as e:
                raise CommandListError(
                    entered_commands, command, e.cli_error_msg)

        return responses

    def save(self, filename='startup-config'):
        command = 'copy running-config %s' % filename
        expect_string = '\[%s\]' % filename
        self.show(command, expect=True, expect_string=expect_string)
        time.sleep(5)
        self.show('\n')
        return True

    def _file_copy_instance(self, src, dest=None, file_system='flash:'):
        if dest is None:
            dest = os.path.basename(src)

        fc = FileTransfer(self.native, src, dest, file_system=file_system)
        return fc

    def file_copy_remote_exists(self, src, dest=None, file_system='flash:'):
        fc = self._file_copy_instance(src, dest, file_system=file_system)

        self._enable()
        if fc.check_file_exists() and fc.compare_md5():
            return True
        return False

    def file_copy(self, src, dest=None, file_system='flash:'):
        fc = self._file_copy_instance(src, dest, file_system=file_system)
        self._enable()
#        if not self.fc.verify_space_available():
#            raise FileTransferError('Not enough space available.')

        try:
            fc.enable_scp()
            fc.establish_scp_conn()
            fc.transfer_file()
        except:
            raise FileTransferError
        finally:
            fc.close_scp_chan()

    def reboot(self, timer=0, confirm=False):
        if confirm:
            def handler(signum, frame):
                raise RebootSignal('Interupting after reload')

            signal.signal(signal.SIGALRM, handler)
            signal.alarm(10)

            try:
                if timer > 0:
                    first_response = self.show('reload in %d' % timer)
                else:
                    first_response = self.show('reload')

                if 'System configuration' in first_response:
                    self.native.send_command('no')

                self.native.send_command('\n')
            except RebootSignal:
                signal.alarm(0)

            signal.alarm(0)
        else:
            print('Need to confirm reboot with confirm=True')

    def _is_catalyst(self):
        return self.facts['model'].startswith('WS-')

    def set_boot_options(self, image_name, **vendor_specifics):
        if self._is_catalyst():
            self.config('boot system flash:/%s' % image_name)
        else:
            self.config_list(['no boot system', 'boot system flash %s' % image_name])

    def get_boot_options(self):
        if self._is_catalyst():
            show_boot_out = self.show('show boot')
            boot_path_regex = r'BOOT path-list\s+:\s+(\S+)'
            boot_path = re.search(boot_path_regex, show_boot_out).group(1)
            boot_image = boot_path.replace('flash:/', '')
            return dict(sys=boot_image)
        else:
            show_boot_out = self.show('show run | inc boot')
            boot_path_regex = r'boot system flash (\S+)'

            match = re.search(boot_path_regex, show_boot_out)
            if match:
                boot_image = match.group(1)
            else:
                boot_image = None
            return dict(sys=boot_image)

    def backup_running_config(self, filename):
        with open(filename, 'w') as f:
            f.write(self.running_config)

    def _uptime_components(self, uptime_full_string):
        match_days = re.search(r'(\d+) days?', uptime_full_string)
        match_hours = re.search(r'(\d+) hours?', uptime_full_string)
        match_minutes = re.search(r'(\d+) minutes?', uptime_full_string)

        days = int(match_days.group(1)) if match_days else 0
        hours = int(match_hours.group(1)) if match_hours else 0
        minutes = int(match_minutes.group(1)) if match_minutes else 0

        return days, hours, minutes

    def _uptime_to_string(self, uptime_full_string):
        days, hours, minutes = self._uptime_components(uptime_full_string)
        return '%02d:%02d:%02d:00' % (days, hours, minutes)

    def _uptime_to_seconds(self, uptime_full_string):
        days, hours, minutes = self._uptime_components(uptime_full_string)

        seconds = days * 24 * 60 * 60
        seconds += hours * 60 * 60
        seconds += minutes * 60

        return seconds

    def _interfaces_detailed_list(self):
        ip_int_br_out = self.show('show ip int br')
        ip_int_br_data = get_structured_data('cisco_ios_show_ip_int_brief.template', ip_int_br_out)

        return ip_int_br_data

    def _show_vlan(self):
        show_vlan_out = self.show('show vlan')
        show_vlan_data = get_structured_data('cisco_ios_show_vlan.template', show_vlan_out)

        return show_vlan_data

    def _raw_version_data(self):
        show_version_out = self.show('show version')
        try:
            version_data = get_structured_data('cisco_ios_show_version.template', show_version_out)[0]
            return version_data
        except IndexError:
            return {}

    def rollback(self, rollback_to):
        try:
            self.show('configure replace flash:%s force' % rollback_to)
        except CommandError:
            raise RollbackError('Rollback unsuccessful. %s may not exist.' % rollback_to)

    def checkpoint(self, checkpoint_file):
        self.save(filename=checkpoint_file)

    @property
    def facts(self):
        if hasattr(self, '_facts'):
            return self._facts

        facts = {}
        facts['vendor'] = self.vendor

        version_data = self._raw_version_data()
        show_version_facts = convert_dict_by_key(version_data, ios_key_maps.BASIC_FACTS_KM)

        facts.update(show_version_facts)

        uptime_full_string = version_data['uptime']
        facts['uptime'] = self._uptime_to_seconds(uptime_full_string)
        facts['uptime_string'] = self._uptime_to_string(uptime_full_string)

        facts['fqdn'] = 'N/A'
        facts['interfaces'] = list(x['intf'] for x in self._interfaces_detailed_list())

        if show_version_facts['model'].startswith('WS'):
            facts['vlans'] = list(str(x['vlan_id']) for x in self._show_vlan())
        else:
            facts['vlans'] = []

        # ios-specific facts
        ios_facts = facts[IOS_SSH_DEVICE_TYPE] = {}
        ios_facts['config_register'] = version_data['config_register']

        self._facts = facts
        return facts

    @property
    def running_config(self):
        return self.show('show running-config', expect=True)

    @property
    def startup_config(self):
        return self.show('show startup-config')
Ejemplo n.º 18
0
logging.basicConfig(filename=f"log/juniper_junos_{dte_string}.log",
                    level=logging.DEBUG)
logging.getLogger().addHandler(logging.StreamHandler())
logger = logging.getLogger("netmiko")

show_command = "show version"
config_commands = []

net_connect = ConnectHandler(**device)
prompt = net_connect.find_prompt()

logger.info(f"prompt: {prompt}")

logger.info(f"Switch into Enable Mode")
net_connect.enable()
enabled = net_connect.check_enable_mode()
logger.info(f"enabled: {enabled}")

logger.info(f"Switch into Config Mode")
net_connect.config_mode()
config_mode = net_connect.check_config_mode()
logger.info(f"config_mode: {config_mode}")

logger.info(f"About to execute show_command")
if show_command == "":
    logger.info(f"show_command is empty")
else:
    logger.info(f"show_command: {show_command}")
    output = net_connect.send_command(show_command)
    logger.info(f"output: {output}")
Ejemplo n.º 19
0
class CiscoDevice:

    def __init__(self):
        device_type = ui.get_device_type_window()
        self.host = ui.get_device_window()
        username, password, secret = ui.get_credentials_window(self.host)
        self.device = {
            'device_type': device_type,
            'host': self.host,
            'username': username,
            'password': password,
            'secret': secret
        }

    def __enter__(self):
        self.remote_conn = ConnectHandler(**self.device)
        return self

    def version(self):
        """Execute show version command."""
        print(f"Version information for: {self.device['host']}")
        print('~' * 100)
        print(self.remote_conn.send_command('show version'))

    @property
    def clock(self):
        """Returns the time and date on the device."""
        print(f"Fetching time information from {self.device['host']}")
        self.remote_conn.enable()
        clock_str = self.remote_conn.send_command('show clock').replace('*', '').strip()
        self.remote_conn.config_mode()
        clock = datetime.strptime(clock_str, '%H:%M:%S.%f %Z %a %b %d %Y')
        clock_utc = pytz.utc.localize(clock)
        return clock_utc.strftime('%H:%M:%S %Z %a %b %d %Y')

    @clock.setter
    def clock(self, datetime_obj):
        """
        Sets the clock of the device using Netmiko.
        :param (datetime_obj): an instance of the datetime.datetime class
        """
        if isinstance(datetime_obj, datetime):
            equipment_date_raw = self.remote_conn.send_command('show clock') \
                .replace('*', '').strip()
            equipment_date = datetime.strptime(
                equipment_date_raw,
                '%H:%M:%S.%f %Z %a %b %d %Y'
            )

            timedelta = abs((equipment_date - datetime_obj).total_seconds())

            if timedelta > 30:
                date = datetime_obj.strftime('%H:%M:%S %d %b %Y')
                print(f"{self.device['host']} - \
                        Clock Offset: {timedelta} seconds. \
                        Setting clock: {date}"
                      )
                self.remote_conn.enable()
                self.remote_conn.send_command(f'clock set {date}')
            else:
                print(f"{self.device['host']} - {equipment_date_raw} - Clock OK")
        else:
            raise ValueError('Must assign a datetime object.')

    @property
    def hostname(self):
        """Returns the hostname of the device."""
        print(f"Fetching hostname information from {self.device['host']}")
        name = self.remote_conn.find_prompt().replace('#', '')
        return name

    @hostname.setter
    def hostname(self, name):
        """
        Sets the hostname of the device.
        :param name: (str) must contain at least one alphabet or '-' or '_' character
        """
        if search('[a-zA-z_-]', name):
            print(f'Setting hostname {name} to {self.host}')
            self.remote_conn.send_command(f'hostname {name}')
            print(self.remote_conn.find_prompt())
        else:
            raise ValueError("Hostname should contain at least one alphabet or '-' or '_' character")

    def get_users(self):
        """Returns a list of configured users."""
        print(f"Fetching users information from {self.device['host']}")
        self.remote_conn.enable()
        users_str = self.remote_conn.send_command('show running-config | include username').split('\n')
        user_list = []
        for line in users_str:
            user_list.append(line.split()[1])
        return user_list

    def add_user(self):
        username, password, privilege = ui.add_user_window(self.host, self.get_current_user_privilege())
        if self.remote_conn.check_enable_mode():
            self.remote_conn.config_mode()
        self.remote_conn.send_command(f'username {username} privilege {privilege} password {password}')

    def delete_user(self):
        user_list = self.get_users()
        user = ui.delete_user_window(self.host, user_list)
        self.remote_conn.config_mode()
        self.remote_conn.send_command(f'no username {user}')

    @property
    def domain(self):
        """Returns the domain name configured on the device."""
        print(f"Fetching domain information from {self.device['host']}")
        domain_name = self.remote_conn.send_command('show running-config | include domain').split()[-1]
        return domain_name

    @domain.setter
    def domain(self, domain_name):
        """
        Sets the domain-name of the device.
        :param domain_name: (str) domain name of the device
        """
        self.remote_conn.send_command(f"ip domain-name {domain_name}")

    def get_current_user_privilege(self):
        self.remote_conn.enable()
        privilege = int(self.remote_conn.send_command('show privilege').split()[-1])
        return privilege


    def save_configuration(self):
        choice = ui.save_configuration_window()
        if choice:
            self.remote_conn.enable()
            self.remote_conn.send_command('write memory')

    def __exit__(self, *args):
        self.remote_conn.disconnect()