def connect_f10(sw_ip): device = ConnectHandler(device_type='dell_force10', ip=str(sw_ip), username=tacacs_username, password=tacacs_password) time.sleep(10) device.clear_buffer() output = device.send_command("sh int | gr Gig|-cha|CRC | except part|Descr|Mini").replace('\n',' ') device.disconnect() a = re.sub(r'\sCRC,\s\d\s\w+,\s\d\s\w+','',output) b = re.sub(r'\sis\s\w+,(\s\w+){1,}','',a) c = re.sub(r'\((\w+\s+){1,}\w+\)','',b) d = re.sub(r'(\s+)(\d+\/)',r'\2',c) e = re.sub(r'(l)(\s+)(\d+)',r'\1\3',d) z = re.sub(r'CRC,\s\d*\s\w*,\s\d*\s\w*','',e) f = re.sub(r'\s+',' ',z).strip().split(' ') convrt_dct = {f[i]: f[i + 1] for i in range(0, len(f), 2)} dctvalue_int = {k:int(v) for k, v in convrt_dct.items()} dct_output = compre_threshold(dctvalue_int) fix_output = { "Switch Model": "F10", "Switch MGT IP": sw_ip, "crc_error_count": dct_output } crc_json = json.dumps(fix_output) return crc_json
def connect_n7k(sw_ip): device = ConnectHandler(device_type='cisco_nxos', ip=str(sw_ip), username=tacacs_username, password=tacacs_password) time.sleep(10) device.clear_buffer() output = device.send_command("sh int | egrep Ethernet|-chann|CRC | exc Ha | exc De") device.disconnect() rem_isupdown = re.sub(r'\s+is.*',r'',output).replace('\n','') rem_admindown = re.sub(r'\((\w+\s+){1,}\w+\)','',rem_isupdown) z = re.sub(r'\(\w+\)',r'',rem_admindown) rem_rntsgiants = re.sub(r'\d+\s+runts\s+\d+\s+giants\s+',r'',z) rem_nbffr = re.sub(r'(r)(E)',r'\1\n\2',rem_rntsgiants) rem_sspndd = re.sub(r'(r)(p)',r'\1\n\2',rem_nbffr) f = re.sub(r'\sCRC.*',r'',rem_sspndd) convrt_to_list = re.sub(r'\s+',r' ',f).strip().split(' ') convrt_dct = {convrt_to_list[i]: convrt_to_list[i + 1] for i in range(0, len(convrt_to_list), 2)} dctvalue_int = {k:int(v) for k, v in convrt_dct.items()} dct_output = compre_threshold(dctvalue_int) fix_output = { "Switch Model": "N7k", "Switch MGT IP": sw_ip, "crc_error_count": dct_output } crc_json = json.dumps(fix_output, sort_keys=True) return crc_json
def connect_n5k(sw_ip): device = ConnectHandler(device_type='cisco_nxos', ip=str(sw_ip), username=tacacs_username, password=tacacs_password) time.sleep(10) device.clear_buffer() output = device.send_command("sh int counters detailed all | incl Ethernet next 68 | exc s | exc o") device.disconnect() mod_out = ''.join(output.split()).replace('44.rxCRC=',' ').replace('--',' ') conv_out = mod_out.split(' ') convrt_dct = {conv_out[i]: conv_out[i + 1] for i in range(0, len(conv_out), 2)} dctvalue_int = {k:int(v) for k, v in convrt_dct.items()} dct_output = compre_threshold(dctvalue_int) fix_output = { "Switch Model": "N5k", "Switch MGT IP": sw_ip, "crc_error_count": dct_output } crc_json = json.dumps(fix_output, sort_keys=True) return crc_json
def fetchpingvalues(devip,destips,cmdend,delay,cmddelay): global resultoutput ttl="0" destip="none" command="" try: output="" device = ConnectHandler(device_type='cisco_ios', ip=devip, username=username, password=password, global_delay_factor=cmddelay) time.sleep(delay) device.clear_buffer() for destip in destips: command="ping "+destip+" source "+devip+cmdend output = device.send_command_timing(command,delay_factor=cmddelay) if ("round-trip" in output): resultoutput[devip+":"+destip]="True" elif ("Success rate is 0 percent" in output): resultoutput[devip+":"+destip]="False" device.disconnect() except: print ("Error connecting to ..."+devip) for destip in destips: resultoutput[devip+":"+destip]="False"
def pingTest(device1, device2, aIntf, bIntf, latencyValue, latency): try: username, password = common.getRouterCredentials() #password="******" delayFactor, loop = common.getSendCommandDelayFactor() timeout = getTimeout() slaState = "0" AEnddevice = ConnectHandler(device_type="cisco_ios", ip=device1, username=username, password=password) command = 'sh run interface ' + aIntf AEnddevice.clear_buffer() output1 = AEnddevice.send_command(command, int(delayFactor), int(loop)) output1 = str(output1) log.info("Device %s. Command %s. Output %s", str(device1), str(command), str(output1)) match = re.match(r'.*ip\s+address\s+(.*)\s+255.*', output1, re.DOTALL) if match: AEndIntf = match.group(1) BEnddevice = ConnectHandler(device_type="cisco_ios", ip=device2, username=username, password=password) command = 'sh run interface ' + bIntf BEnddevice.clear_buffer() output1 = BEnddevice.send_command(command, int(delayFactor), int(loop)) output1 = str(output1) log.info("Device %s. Command %s. Output %s", str(device2), str(command), str(output1)) match = re.match(r'.*ip\s+address\s+(.*)\s+255.*', output1, re.DOTALL) if match: BEndIntf = match.group(1) command = 'ping ' + BEndIntf.strip() + ' source ' + AEndIntf.strip( ) + ' repeat 30 timeout ' + timeout AEnddevice.clear_buffer() output1 = AEnddevice.send_command(command, int(delayFactor), int(loop)) output1 = str(output1) pingA = output1 log.info("Device %s.Ping Command %s. Output %s", str(device1), str(command), str(output1)) Alatency = 1 pingResultA = -1 match = re.match(r'.*rate\s+is\s+(.*)\s+percent.*', output1, re.DOTALL) if match: pingResultA = match.group(1) try: if "latency" in latency.lower(): lValue = latencyValue.split(",") match1 = re.match( r'.*min/avg/max\s*=\s*(\d+)/(\d+)/(\d+).*', output1, re.DOTALL) if match1: AminValue = match1.group(1) AavgValue = match1.group(2) AmaxValue = match1.group(3) if int(lValue[0]) > int(AavgValue) or int( lValue[2]) < int(AavgValue): if int(lValue[0]) > int(AavgValue) and int( lValue[2]) < int(AavgValue): slaState = "Latency-Above & Below threshold" elif int(lValue[0]) > int(AavgValue): slaState = "Latency-Below threshold" else: slaState = "Latency-Above threshold" Alatency = 0 except Exception as e: log.warning( "parsing Latency Message got failed.Error info : %s", str(e)) else: if "Invalid" in output1: pingResultA = "0" elif pingResultA == -1: pingResultA = output1 # pingResultA="0" command = 'ping ' + AEndIntf.strip() + ' source ' + BEndIntf.strip( ) + ' time ' + timeout + ' repeat 30' BEnddevice.clear_buffer() output1 = BEnddevice.send_command(command, int(delayFactor), int(loop)) output1 = str(output1) pingB = output1 print "PingB", pingB log.info("Device %s. Ping Command %s. Output %s", str(device2), str(command), str(output1)) Blatency = 1 pingResultB = -1 match = re.match(r'.*rate\s+is\s+(.*)\s+percent.*', output1, re.DOTALL) if match: pingResultB = match.group(1) try: if "latency" in latency.lower(): lValue = latencyValue.split(",") match1 = re.match( r'.*min/avg/max\s*=\s*(\d+)/(\d+)/(\d+).*', output1, re.DOTALL) if match1: BminValue = match1.group(1) BavgValue = match1.group(2) BmaxValue = match1.group(3) if int(lValue[0]) > int(BavgValue) or int( lValue[2]) < int(BavgValue): if int(lValue[0]) > int( BavgValue) and lValue[2] < int(BavgValue): slaState = "Latency-Above & Below threshold" elif int(lValue[0]) > int(BavgValue): slaState = "Latency-Below threshold" else: slaState = "Latency-Above threshold" Blatency = 0 except Exception as e: log.warning( "parsing Latency Message got failed.Error info : %s", str(e)) else: if "Invalid" in output1: pingResultB = "0" elif pingResultB == -1: pingResultB = output1 try: log.info( "Ping result success rate for A ENd Device : %s , For Z End Device : %s ", str(pingResultA), str(pingResultB)) if int(pingResultA.strip()) > 99 and int(pingResultB.strip()) > 99: if Blatency == 0 or Alatency == 0: return 0, AEndIntf, BEndIntf, pingA, pingB, slaState else: return 1, AEndIntf, BEndIntf, pingA, pingB, slaState else: return 0, AEndIntf, BEndIntf, pingA, pingB, slaState except Exception as e: return 0, AEndIntf, BEndIntf, pingA, pingB, slaState except Exception as e: if "Authentication" in str(e): subject = "Authentication failed on routers" + device1 + "," + device2 message = "Error while login to Routers.Authentication failed" sendMail(subject, message, 'exception') return 0, 0, 0, "Fail", 0, "" elif "timed-out" in str(e): log.warning("Device timed out error %s", str(e)) return 0, 0, 0, "0", 0, "" else: log.warning("Error occured while doing pingtest %s", str(e))
"NETMIKO_PASSWORD") else getpass() if __name__ == "__main__": debug = True device = { "device_type": "cisco_ios", "host": "cisco4.lasthop.io", "username": "******", "password": password, } net_connect = ConnectHandler(**device) print(f"\nCurrent Prompt:\n{net_connect.find_prompt()}\n") print("Enter into configuration mode:") output = net_connect.config_mode() net_connect.clear_buffer() print(f"\nCurrent Prompt:\n{net_connect.find_prompt()}\n") new_hostname = "cisco4-testing" net_connect.write_channel(f"hostname {new_hostname}\n") print("Exit configuration mode:") output = net_connect.exit_config_mode() # Should reset Netmiko's base prompt if you change the hostname net_connect.set_base_prompt() print(f"\nCurrent Prompt:\n{net_connect.find_prompt()}\n")
import logging import time logging.basicConfig(filename='test.log', level=logging.DEBUG) loger = logging.getLogger("netmiko") tplink_t1600 = { 'device_type': 'tplink_jetstream', 'host': '192.168.10.252', 'username': '******', 'password': '******', 'port': 22, 'verbose': True, } connection = ConnectHandler(**tplink_t1600) prompt = connection.find_prompt() print(prompt) if '>' in prompt: connection.enable() # entering the enable mode # print(connection.base_prompt) time.sleep(3) connection.clear_buffer() output = connection.send_command(command_string='show mac-vlan all') print(output) # closing the connection print('Closing connection') connection.disconnect()
class NetmikoSSH(object): """Contains methods for managing and using SSH connections for Network Devices using Netmiko""" __MAX_RECV_BUF = 10 * 1024 * 1024 __existing_connections = {} def __init__(self): self._session = None self._node = None self._device = {} @staticmethod def _node_hash(node, port): """Get IP address and port hash from node dictionary. :param node: Node in topology. :param port: :type node: dict :return: IP address and port for the specified node. :rtype: int """ return hash(frozenset([node['mgmt_ip'], port])) @staticmethod def _get_device_type(node): device_os = node['os'] if str(device_os) in os_netmiko_map.keys(): return os_netmiko_map[str(device_os)] return None def net_connect(self, node): """Connect to node using Netmiko's inbuilt libraries. :param node: The node to disconnect from. :type node: dict """ self._node = node ssh_port = Topology.get_ssh_port_from_node(node) node_hash = NetmikoSSH._node_hash(node, ssh_port) if node_hash in NetmikoSSH.__existing_connections: self._session = NetmikoSSH.__existing_connections[node_hash] logger.debug('reusing ssh: {0}'.format(self._session)) else: start = time() self._device = { 'device_type': NetmikoSSH._get_device_type(node), 'ip': node['mgmt_ip'], 'username': node['username'], 'password': node['password'], 'port': ssh_port } self._session = ConnectHandler(**self._device) NetmikoSSH.__existing_connections[node_hash] = self._session logger.trace('connect took {} seconds'.format(time() - start)) logger.debug('new connection: {0}'.format(self._session)) logger.debug('Connections: {0}'.format( str(NetmikoSSH.__existing_connections))) def net_disconnect(self, node): """Close SSH connection to the node. :param node: The node to disconnect from. :type node: dict """ ssh_port = Topology.get_ssh_port_from_node(node) node_hash = NetmikoSSH._node_hash(node, ssh_port) if node_hash in NetmikoSSH.__existing_connections: logger.debug('Disconnecting peer: {}, {}'.format( node['name'], ssh_port)) ssh = NetmikoSSH.__existing_connections.pop(node_hash) self._session.disconnect() def _reconnect(self): """Close the SSH connection and open it again.""" node = self._node self.net_disconnect(node) self.net_connect(node) def config_mode(self): """Enter into config mode """ self.net_connect(self._node) self._session.config_mode() def check_config_mode(self): """ Check if session is currently in config mode""" self.net_connect(self._node) return self._session.check_config_mode() def exit_config_mode(self): """Exit config mode""" self.net_connect(self._node) self._session.exit_config_mode() def clear_buffer(self): """ Clear logging buffer """ self.net_connect(self._node) self._session.clear_buffer() def enable(self): """ Enter Enable Mode""" self.net_connect(self._node) self._session.enable() def exit_enable_mode(self): """ Exit enable mode """ self.net_connect(self._node) self._session.exit_enable_mode() def find_prompt(self): """Return the current router prompt""" self.net_connect(self._node) self._session.find_prompt() def send_command(self, cmd): """Send command down the SSH channel and return output back :param cmd :type cmd: str """ if cmd is None: raise TypeError('Command parameter is None') if len(cmd) == 0: raise ValueError('Empty command parameter') self.net_connect(self._node) return self._session.send_command(cmd) def send_config_set(self, config_cmds): """Send a set of configuration commands to remote device :param config_cmds :type config_cmds: str """ if config_cmds is None: raise TypeError('Config Cmds parameter is None') self.net_connect(self._node) print "Netmiko NODE !!!\n\n" print self._node return self._session.send_config_set(config_cmds) def send_config_from_file(self, cfg_file): """Send a set of configuration commands loaded from a file :param cfg_file :type cfg_file: file """ if not os.path.isfile(cfg_file): raise TypeError('Config file does not exist') self.net_connect(self._node) self._session.send_config_from_file(cfg_file)
class CiscoSwitch(object): """Cisco switch control.""" # pylint: disable=len-as-condition # Parsing command line output has uncertain lengths MAX_COMMAND_READ = 16 CMD_VERSION = "sh version" CMD_VERSION_SIGNALS = ["BOOTLDR"] CMD_IPDT = "sh ip device track all" CMD_MAC_ADDRESS_TABLE = "sh mac address-table" CMD_POWER_OFF = "power inline never" CMD_POWER_ON = "power inline auto" CMD_POWER_LIMIT = "power inline {0} max {1}" CMD_POWER_LIMIT_AUTO = "auto" CMD_POWER_LIMIT_STATIC = "static" CMD_POWER_SHOW = "sh power inline {0}" CMD_CONFIGURE_INTERFACE = "int {0}" CMD_VLAN_MODE_ACCESS = "switchport mode access" CMD_VLAN_SET = "switchport access vlan {0}" CMD_VLAN_SHOW = "sh vlan" CMD_CARRIAGE_RETURN = "\n" PORT_NOTATION = { "fastethernet": "Fa", "gigabitethernet": "Gi", "tengigabitethernet": "Ten", } def __init__(self, hostname_or_ip_address, username, password): """Initialize the CiscoSwitch object. :param hostname_or_ip_address: host name or ip address :param username: username to login with :param password: password to use with username :return: CiscoSwitch object """ self._host = hostname_or_ip_address self._version = None self._username = username self._password = password self._client = None self._logger = logging.getLogger(__name__) self._logger.addHandler(logging.NullHandler()) def connect(self): """Connect to the switch. :return: """ self._client = ConnectHandler( device_type="cisco_ios", ip=self._host, username=self._username, password=self._password, ) def disconnect(self): """Disconnect from the switch. :return: """ if self._client is not None: self._client.disconnect() self._client = None def enable(self, password): """Put the switch in enable mode. :param password: password to use to enable :return: """ if not self.connected: return self._client.secret = password self._client.enable() @deprecated def set_terminal_length(self): """Set terminal length. :return: """ pass def ipdt(self): """IP Device Tracking (IPDT) information. :return: IPDT information """ if not self.connected: return None output = self._send_command(self.CMD_IPDT) return self._parse_ipdt_output(output) def mac_address_table(self, ignore_port=None): """MAC Address Table Information. :param ignore_port: port to ignore, e.g. Gi1/0/48 :return: ARP information """ if not self.connected: return None output = self._send_command(self.CMD_MAC_ADDRESS_TABLE) return self._parse_mac_address_table_output( output, ignore_port=ignore_port ) def poe_on(self, port): """Enable a port for POE. :param port: port to enable POE on, e.g. Gi1/0/1 :return: True if the command succeeded, False otherwise """ if not self.connected: return False port = self._shorthand_port_notation(port) cmds = [self.CMD_CONFIGURE_INTERFACE.format(port), self.CMD_POWER_ON] self._send_config(cmds) verify = self._send_command(self.CMD_POWER_SHOW.format(port)) matches, _, _ = CiscoSwitch._verify_poe_status(verify, port, "on") return matches def poe_off(self, port): """Disable a port for POE. :param port: port to disable POE on, e.g. Gi1/0/1 :return: True if the command succeeded, False otherwise """ if not self.connected: return False port = self._shorthand_port_notation(port) cmds = [self.CMD_CONFIGURE_INTERFACE.format(port), self.CMD_POWER_OFF] self._send_config(cmds) verify = self._send_command(self.CMD_POWER_SHOW.format(port)) matches, _, _ = CiscoSwitch._verify_poe_status(verify, port, "off") return matches def poe_limit(self, port, milliwatts_limit, static=True): """Enable a port for POE, but limit the maximum wattage. The default option used is "static", because it ensures the power limit is set regardless. The side-effect is that this is likely to remove and reapply power to the port if it is currently set to "auto", cycling any powered device (PD) connected to it. :param port: port to enable POE on, e.g. Gi1/0/1 :param milliwatts_limit: the maximum wattage, given in milliwatts, e.g. 15400. Cisco documentation gives 4000 to 30000 as the valid range. :param static: whether to use the "static" option (default) or "auto" """ if not self.connected: return False option = ( self.CMD_POWER_LIMIT_STATIC if static else self.CMD_POWER_LIMIT_AUTO ) port = self._shorthand_port_notation(port) cmds = [ self.CMD_CONFIGURE_INTERFACE.format(port), self.CMD_POWER_LIMIT.format(option, milliwatts_limit), ] self._send_config(cmds) verify = self._send_command(self.CMD_POWER_SHOW.format(port)) matches, _, _ = CiscoSwitch._verify_poe_status(verify, port, option) return matches def is_poe(self, port): """Get the POE state for a port. :param port: port to determine state of, e.g. Gi1/0/1 :return: milliwatts_limit (a non-zero integer), evaluating to True if POE is enabled, else 0 (False). """ if not self.connected: return 0 port = self._shorthand_port_notation(port) verify = self._send_command(self.CMD_POWER_SHOW.format(port)) _, poe, limit = CiscoSwitch._verify_poe_status(verify, port, "unknown") return 0 if poe == "off" else limit def change_vlan(self, port, vlan): """Change the VLAN assignment on a port. :param port: port to change VLAN assignment on, e.g. Gi1/0/1 :param vlan: VLAN id :return: True if the command succeeded, False otherwise """ if not self.connected: return False port = self._shorthand_port_notation(port) cmds = [ self.CMD_CONFIGURE_INTERFACE.format(port), self.CMD_VLAN_MODE_ACCESS, self.CMD_VLAN_SET.format(int(vlan)), ] self._send_config(cmds) verify = self._send_command(self.CMD_VLAN_SHOW) matches, _ = CiscoSwitch._verify_vlan_status(verify, port, int(vlan)) return matches def vlan(self, port): """Get the VLAN assignment on a port. :param port: port to determine VLAN assignment on, e.g. Gi1/0/1 :return: VLAN id """ if not self.connected: return -1 port = self._shorthand_port_notation(port) verify = self._send_command(self.CMD_VLAN_SHOW) _, vlan = CiscoSwitch._verify_vlan_status(verify, port, 0) return vlan @property def version(self): """Retrieve the Cisco IOS version. :return: The Cisco IOS version. """ if not self.connected: return None if self._version is None: output = self._send_command(self.CMD_VERSION) self._version = self._parse_version_output(output) return self._version @property def host(self): """Retrieve the IP address or hostname of the switch. :return: IP address or hostname of the switch """ return self._host @property def connected(self): """Switch connection status. :return: has a connection to the switch been made? """ if self._client is None: return False self._send_command(self.CMD_CARRIAGE_RETURN) active_ssh = True try: self._client.find_prompt() except ValueError: active_ssh = False return active_ssh def _shorthand_port_notation(self, port): """Shorthand port notation. Takes a port name, such as Gi1/0/48 or GigabitEthernet1/0/48 and returns the shorthand notation. :param port: port name :return: shorthand port name """ if port is None: return "" lower = port.lower() output = port if any(lower.find(port) == 0 for port in self.PORT_NOTATION): for item in self.PORT_NOTATION.items(): if lower.startswith(item[0]): output = lower.replace(item[0], item[1]) break return output def _send_command(self, command): """Send command. Sends a command to the switch. :param command: command to send :return: output of the command """ read_buffer = "" if self._client is None: return read_buffer self._client.clear_buffer() read_buffer = self._client.send_command(command) return read_buffer def _send_config(self, configs): """Configure switch. Sends a series of configuration options to the switch. :param configs: config commands """ if self._client is None: return self._client.clear_buffer() self._client.send_config_set(configs) @staticmethod def _parse_version_output(output): """Version parsing. :param output: the output of the command :return: version string """ lines = [line.strip() for line in output.splitlines()] version = "" search = True while len(lines) > 0 and search: line = lines.pop() if line.find("Cisco IOS") < 0: continue version_info = line.split(",") if len(version_info) > 1: version = version_info[2].strip() version = version[8:] search = False return version def _parse_mac_address_table_output(self, output, ignore_port=None): """MAC Address Table parsing. Parses the output of 'sh mac address-table' command. :param output: the output of the command Mac Address Table ------------------------------------------- Vlan Mac Address Type Ports ---- ----------- -------- ----- All 0100.0ccc.cccc STATIC CPU <snip> All ffff.ffff.ffff STATIC CPU 601 000b.7866.5240 DYNAMIC Gi1/0/48 601 0013.20fe.56b4 DYNAMIC Gi1/0/35 <snip> Total Mac Addresses for this criterion: 59 :param ignore_port: ignore this port :return: list of dicts containing device connection metrics """ lookup = [] lines = [line.strip() for line in output.splitlines()] lines.append("") while len(lines) > 0: line = lines.pop(0) # Table entries will always have a '.' for the MAC address. # If there isn't one it's not a row we care about. if line.find(".") < 0: continue values = [entry for entry in line.split() if entry] # Ignore non-physical ports port_types = self.PORT_NOTATION.values() if all( values[3].lower().find(port.lower()) != 0 for port in port_types ): continue # If the ignore_port is specified and is the port in question, # ignore it. ignore_port = self._shorthand_port_notation(ignore_port) if ignore_port is not None and ignore_port == values[3]: continue lookup.append( { "mac": EUI(values[1], dialect=mac_unix_expanded), "interface": self._shorthand_port_notation(values[3]), } ) return sorted(lookup, key=lambda k: k["interface"]) def _parse_ipdt_output(self, output): """IPDT output parsing. Parses the output of the `show ip device track` command. :param output: the output of the command IP Device Tracking = Enabled IP Device Tracking Probe Count = 3 IP Device Tracking Probe Interval = 30 IP Device Tracking Probe Delay Interval = 0 ------------------------------------------------------------------- IP Address MAC Address Vlan Interface STATE ------------------------------------------------------------------- 192.168.1.12 6cec.eb68.c86f 601 GigabitEthernet1/0/14 ACTIVE 192.168.1.15 6cec.eb67.836c 601 GigabitEthernet1/0/12 ACTIVE <snip> Total number interfaces enabled: 47 Enabled interfaces: Gi1/0/1, Gi1/0/2, Gi1/0/3, Gi1/0/4, Gi1/0/5, Gi1/0/6, Gi1/0/7, <snip> :return: list of dicts containing device connection metrics """ lookup = [] lines = [line.strip() for line in output.splitlines()] lines.append("") while len(lines) > 0: line = lines.pop(0) # Table entries will always have a '.' for the MAC address. # If there isn't one it's not a row we care about. if line.find(".") < 0: continue values = [entry for entry in line.split() if entry] # Ignore any 'INACTIVE' entries, meaning that there hasn't been # traffic from that MAC Address is has likely been unplugged. if values[4] == "INACTIVE": continue lookup.append( { "ip": values[0], "mac": EUI(values[1], dialect=mac_unix_expanded), "interface": self._shorthand_port_notation(values[3]), } ) return sorted(lookup, key=lambda k: k["interface"]) @staticmethod def _verify_poe_status(output, port, state): """Verify that the given port is in the given state. :param output: the output of the command Interface Admin Oper Power Device Class Max (Watts) --------- ------ ---------- ------- ------------------- ----- ---- Gi2/0/16 auto on 15.4 Ieee PD 0 30.0 Interface AdminPowerMax AdminConsumption (Watts) (Watts) ---------- --------------- -------------------- Gi2/0/16 30.0 15.4 :param port: port to check :param state: expected state :return: (True, actual_state, milliwatts_limit) if the port is in the expected state, (False, actual_state, milliwatts_limit) otherwise. """ if "on" in state: state = "auto" matches = False lines = [line.strip() for line in output.splitlines()] lines.append("") actual_state = "unknown" milliwatts_limit = 0 while len(lines) > 0: line = lines.pop(0) # Table entries will always have a '/' for the interface. # If there isn't one it's not a row we care about. if line.find("/") < 0: continue values = [entry for entry in line.split() if entry] # Is this the port of interest? if values[0] != port: continue matches = state in values[1] actual_state = values[1] # The last column, "Max", gives Watts to the to tenths spot milliwatts_limit = int(float(values[-1]) * 1000.0) break return matches, actual_state, milliwatts_limit @staticmethod def _verify_vlan_status(output, port, vlan): """Verify that the given port is assigned to the given vlan. :param output: VLAN Name Status Ports ---- -------------------------------- --------- ------------------ 1 default active Te1/0/1, Te1/0/2 701 NET-701 active Gi1/0/1, Gi1/0/2 702 NET-702 active Gi1/0/8 703 NET-703 active Gi1/0/7, Gi1/0/10 704 NET-704 active Gi1/0/5, Gi1/0/9 705 NET-705 active :param port: port to check :param vlan: expected vlan :return: (True, actual vlan #) if the port is assigned to the expected vlan, (False, actual vlan #) otherwise """ matches = False lines = [line.strip() for line in output.splitlines()] lines.append("") actual_vlan = -1 current_vlan = -1 while len(lines) > 0: line = lines.pop(0).replace(",", "") # Table entries will have a '/' for the ports. # If there isn't one it's not a row we care about, even if it's a # vlan with no ports assigned to it. if line.find("/") < 0: continue values = [entry for entry in line.split() if entry] if "active" in values: current_vlan = int(values[0]) ports = values[3:] else: ports = values # Is the port of interest in the list of ports? if port not in ports: continue actual_vlan = current_vlan if actual_vlan == vlan: matches = True return matches, actual_vlan
def pingTest(device1,device2,aIntf,bIntf,latencyValue,latency): try: username,password=common.getRouterCredentials() #password="******" delayFactor,loop = common.getSendCommandDelayFactor() timeout=getTimeout() slaState="0" AEnddevice = ConnectHandler(device_type="cisco_ios", ip=device1, username=username, password=password) command='sh run interface '+aIntf AEnddevice.clear_buffer() output1 = AEnddevice.send_command(command,int(delayFactor),int(loop)) output1 = str(output1) log.info("Device %s. Command %s. Output %s",str(device1),str(command),str(output1)) match=re.match(r'.*ip\s+address\s+(.*)\s+255.*',output1,re.DOTALL) if match: AEndIntf=match.group(1) BEnddevice = ConnectHandler(device_type="cisco_ios", ip=device2, username=username, password=password) command='sh run interface '+bIntf BEnddevice.clear_buffer() output1 = BEnddevice.send_command(command,int(delayFactor),int(loop)) output1 = str(output1) log.info("Device %s. Command %s. Output %s",str(device2),str(command),str(output1)) match=re.match(r'.*ip\s+address\s+(.*)\s+255.*',output1,re.DOTALL) if match: BEndIntf=match.group(1) command='ping '+BEndIntf.strip()+' source '+AEndIntf.strip()+' repeat 30 timeout '+timeout AEnddevice.clear_buffer() output1 = AEnddevice.send_command(command,int(delayFactor),int(loop)) output1 = str(output1) pingA = output1 log.info("Device %s.Ping Command %s. Output %s",str(device1),str(command),str(output1)) Alatency=1 pingResultA=-1 match=re.match(r'.*rate\s+is\s+(.*)\s+percent.*',output1,re.DOTALL) if match: pingResultA=match.group(1) try: if "latency" in latency.lower(): lValue=latencyValue.split(",") match1=re.match(r'.*min/avg/max\s*=\s*(\d+)/(\d+)/(\d+).*',output1,re.DOTALL) if match1: AminValue=match1.group(1) AavgValue=match1.group(2) AmaxValue=match1.group(3) if int(lValue[0]) > int(AavgValue) or int(lValue[2]) < int(AavgValue): if int(lValue[0]) > int(AavgValue) and int(lValue[2]) < int(AavgValue): slaState="Latency-Above & Below threshold" elif int(lValue[0]) > int(AavgValue): slaState="Latency-Below threshold" else: slaState="Latency-Above threshold" Alatency=0 except Exception as e: log.warning("parsing Latency Message got failed.Error info : %s",str(e)) else: if "Invalid" in output1: pingResultA="0" elif pingResultA == -1: pingResultA = output1 # pingResultA="0" command='ping '+AEndIntf.strip()+' source '+BEndIntf.strip()+' time '+timeout+' repeat 30' BEnddevice.clear_buffer() output1 = BEnddevice.send_command(command,int(delayFactor),int(loop)) output1 = str(output1) pingB = output1 print "PingB",pingB log.info("Device %s. Ping Command %s. Output %s",str(device2),str(command),str(output1)) Blatency=1 pingResultB=-1 match=re.match(r'.*rate\s+is\s+(.*)\s+percent.*',output1,re.DOTALL) if match: pingResultB=match.group(1) try: if "latency" in latency.lower(): lValue=latencyValue.split(",") match1=re.match(r'.*min/avg/max\s*=\s*(\d+)/(\d+)/(\d+).*',output1,re.DOTALL) if match1: BminValue=match1.group(1) BavgValue=match1.group(2) BmaxValue=match1.group(3) if int(lValue[0]) > int(BavgValue) or int(lValue[2]) < int(BavgValue): if int(lValue[0]) > int(BavgValue) and lValue[2] < int(BavgValue) : slaState="Latency-Above & Below threshold" elif int(lValue[0]) > int(BavgValue): slaState="Latency-Below threshold" else: slaState="Latency-Above threshold" Blatency=0 except Exception as e: log.warning("parsing Latency Message got failed.Error info : %s",str(e)) else: if "Invalid" in output1: pingResultB="0" elif pingResultB == -1: pingResultB = output1 try: log.info("Ping result success rate for A ENd Device : %s , For Z End Device : %s ",str(pingResultA),str(pingResultB)) if int(pingResultA.strip()) > 99 and int(pingResultB.strip()) > 99: if Blatency == 0 or Alatency == 0: return 0,AEndIntf,BEndIntf,pingA,pingB,slaState else: return 1,AEndIntf,BEndIntf,pingA,pingB,slaState else: return 0,AEndIntf,BEndIntf,pingA,pingB,slaState except Exception as e: return 0,AEndIntf,BEndIntf,pingA,pingB,slaState except Exception as e: if "Authentication" in str(e): subject="Authentication failed on routers"+device1+","+device2 message="Error while login to Routers.Authentication failed" sendMail(subject,message,'exception') return 0,0,0,"Fail",0,"" elif "timed-out" in str(e): log.warning("Device timed out error %s",str(e)) return 0,0,0,"0",0,"" else: log.warning("Error occured while doing pingtest %s",str(e))