def connect(ne_addr, ne_username, ne_password): # check to see if ne_addr is a valid IP(v6) address if not (HostIpCheck(ne_addr).is_ipv4() or HostIpCheck(ne_addr).is_ipv6()): raise ValueError('%s is not a valid IP address' % ne_addr) # TLS Connection (This is the TLS Pinning Handler) class PinningHandler(tlspinning.TLSUnverifiedElementHandler): def __init__(self, pinning_file): self.pinning_file = pinning_file def handle_verify(self, host, hashtype, finger_print, changed): return tlspinning.DecisionType.ACCEPT_ONCE # Connection to my onePK enabled Network Element config = SessionConfig(None) config.set_tls_pinning('', PinningHandler('')) config.transportMode = SessionConfig.SessionTransportMode.TLS network_element = NetworkElement(ne_addr) # Try authenticating, raise error if unsuccessful try: network_element.connect(ne_username, ne_password, config) except OnepConnectionException: raise ValueError('Invalid Credentials or unable to reach %s.' % network_element) return network_element
def connect(self, applicationName): """ Obtains a NetworkApplication instance, sets the name to applicationName, gets a network element for the IP address in the command line arguments or tutorial.properties file - both via the string format and an InetAddress formed from the IP address string - and then tries to connect to the Network Element with the username and password supplied, or from the tutorial.properties file. @param applicationName: The NetworkApplication name is set to this value. @return True if the connection succeeded without exception, else false. @throws OnepException """ # START SNIPPET: init_myapp network_application = NetworkApplication.get_instance() # END SNIPPET: init_myapp # START SNIPPET: name_myapp network_application.name = applicationName # END SNIPPET: name_myapp # START SNIPPET: get_ne_opt1 self.network_element = network_application.get_network_element(self.element_address) # END SNIPPET: get_ne_opt1 if self.network_element == None: logger.error("Failed to get network element") sys.exit(1) logger.info("We have a NetworkElement : " + self.network_element.__str__()) # START SNIPPET: connect session_config = SessionConfig(SessionConfig.SessionTransportMode.TLS) #default is TLS if self.transport.lower() == "tcp" or self.transport == "0": session_config = SessionConfig(SessionConfig.SessionTransportMode.SOCKET) elif self.transport.lower() == "tipc" or self.transport == "2": session_config = SessionConfig(SessionConfig.SessionTransportMode.TIPC) # Set the path to the root CA certificates session_config.caCerts = self.root_cert_path self.session_handle = self.network_element.connect(self.username, self.password, session_config) # END SNIPPET: connect if self.session_handle == None: # START SNIPPET: loggerError logger.error("Failed to connect to NetworkElement - ") # END SNIPPET: loggerError return False logger.info("Successful connection to NetworkElement - " ) return True
def __init__(self, networkElement, protocol): """ For internal use only """ super(EventManager, self).__init__() self.log = logging.getLogger(__name__) if networkElement != None and networkElement.session_handle != None and networkElement.session_handle.sessionProp != None: self.sessionProp = networkElement.session_handle.sessionProp else: self.sessionProp = SessionProperty(SessionConfig(None), networkElement) self.element = networkElement self.element_evt_processor = onep.NetworkEventIDL.NetworkEventIDL.Processor(self) self.topology_evt_processor = onep.TopologyEventIDL.TopologyEventIDL.Processor(self) self.location_evt_processor = onep.LocationEventIDL.LocationEventIDL.Processor(self) self.routing_evt_processor = onep.RoutingEventIDL.RoutingEventIDL.Processor(self) self.bulk_evt_processor = PolicyEventIDL.Processor(self) self.cs_evt_processor = ContainerServicesEventIDL.Processor(self) self.event_queue = collections.deque(maxlen=self.sessionProp.eventQueueSize) self.dedicated_event_queue_map = None self.dedicated_dispatcher_map = None self.listener_map = {} self.listener_client_data_map = {} self.vty_listener_map = {} self.vty_listener_client_data_map = {} self.bulk_listener_map = {} self.evt_protocol = None self.dispatchers = [] self.terminated = False self.ka_monitor = None self.event_id = 200 self.start_listeners(protocol)
def ConnectNE(): global frame global connect_attempt global ne global username global password ne = NetworkElement(router_ip, connection_name) config = SessionConfig(None) config.set_tls_pinning("", PinningHandler("")) config.transportMode = SessionConfig.SessionTransportMode.TLS if ne.is_connected() != 1: try: ne.connect(username, password, config) except: connect_attempt = connect_attempt + 1 ConnectNE()
def sampleapp(): appname = raw_input('Enter name of application : ') session_config = SessionConfig(SessionConfig.SessionTransportMode.TLS) #default is TLS if transport.lower() == "tipc" or transport == 2: session_config = SessionConfig(SessionConfig.SessionTransportMode.TIPC) session_config.ca_certs = root_cert_path session_config.certfile = client_cert_path session_config.keyfile = client_key_path ne = NetworkElement(switchIP, appname) con = ne.connect(username, password, session_config) print 'Connected to host' print "System Name: ", ne.properties.sys_name print "System Uptime: ", ne.properties.sys_uptime print "Total System Memory: ", ne.total_system_memory print "Free System Memory: ", ne.free_system_memory print "System CPU Utilization: ", ne.system_cpu_utilization, "%\n" print "System Connect Time: ", ne.get_connect_time() print "System Disonnect Time: ", ne.get_disconnect_time() print "System __str__ Method: ", ne print "Host Content String:\n", ne.properties.content_string ne.disconnect()
def jconnect(self): session_config = SessionConfig(SessionConfig.SessionTransportMode.TLS) session_config.ca_certs = "/home/cisco/ca.pem" ne = self.myapp.get_network_element(self.address) if not ne.is_connected(): try: #print 'Trying to connect...' session_handle = ne.connect(self.username, self.password, session_config) #print 'Connection made to ' + self.address + ' successfully.' except OnepDuplicateElementException, e: #print e existing = e.get_original_network_element() #print existing print 'Unable to connect to device.' except Exception, e: #print e print 'Could not connect to ' + self.address + '. Please validate reachability.' return 'DNE'
def jconnect(self): session_config = SessionConfig(SessionConfig.SessionTransportMode.TLS) session_config.ca_certs = "/home/cisco/ca.pem" ne = self.myapp.get_network_element(self.address) if not ne.is_connected(): try: # print 'Trying to connect...' session_handle = ne.connect(self.username, self.password, session_config) # print 'Connection made to ' + self.address + ' successfully.' except OnepDuplicateElementException, e: # print e existing = e.get_original_network_element() # print existing print "Unable to connect to device." except Exception, e: # print e print "Could not connect to " + self.address + ". Please validate reachability." return "DNE"
def connect(self): session_config = SessionConfig( SessionConfig.SessionTransportMode.TLS) session_config.ca_certs = "/usr/local/certs/csr1kv-01.pem" ne = self.myapp.get_network_element(self._host) if not ne.is_connected(): try: session_handle = ne.connect( self._username, self._password, session_config) self._connected = True except OnepDuplicateElementException, e: # print e existing = e.get_original_network_element() # print existing print ('Unable to connect to device.') except Exception, e: # print e print('Could not connect to {0} Please validate reachability.'.format(self._host)) return 'DNE'
def scaleNotification(): for switch in switches: switchIP = switch[0] appName = switch[1] user = switch[2] pswd = switch[3] # # Set up session connection configuration and connect to the switch # ne = NetworkElement(switchIP, appName) if transport == 'TLS': session_config = SessionConfig( SessionConfig.SessionTransportMode.TLS) session_config.ca_certs = cert ne.connect(user, pswd, session_config) elif transport == 'TIPC': session_config = SessionConfig( SessionConfig.SessionTransportMode.TIPC) ne.connect(user, pswd, session_config) else: print "Please set-up a valid transport type: TIPC or TLS" exit(0) vty = VtyService(ne) vty.open() vlan_summary = vty.write("sh vlan summary") vty.close() vlan_sum = re.search('(?<=vlansum-all-vlan\t)(.*)', vlan_summary) if int(vlan_sum.group(0)) > int(scale_limits["max_vlans"]): string_print = "Vlan scale exceeded. Max vlan recommended:", scale_limits[ "max_vlans"], "vlan being used :", vlan_sum.group(0) print string_print ne.create_syslog_message( ne.OnepSyslogSeverity.ONEP_SYSLOG_CRITICAL, str(string_print)) print "Disconnecting from NE: ", switchIP ne.disconnect()
def __init__(self, ip, username='******', password='******'): self.ip = ip self.username = username self.password = password self.myapp = NetworkApplication.get_instance() if not self.myapp.name == 'onePK-Python-Course-app': self.myapp.name == 'onePK-Python-Course-app' self.session_config = SessionConfig( SessionConfig.SessionTransportMode.TLS) self.session_config.ca_certs = "/home/cisco/ca.pem"
def connect(self): session_config = SessionConfig( SessionConfig.SessionTransportMode.TLS) session_config.ca_certs = "/usr/local/certs/csr1kv-01.pem" ne = self.myapp.get_network_element(self._host) if not ne.is_connected(): try: session_handle = ne.connect(self._username, self._password, session_config) self._connected = True except OnepDuplicateElementException, e: # print e existing = e.get_original_network_element() # print existing print('Unable to connect to device.') except Exception, e: # print e print( 'Could not connect to {0} Please validate reachability.' .format(self._host)) return 'DNE'
def scaleNotification(): for switch in switches: switchIP = switch[0] appName = switch[1] user = switch[2] pswd = switch[3] # # Set up session connection configuration and connect to the switch # ne = NetworkElement(switchIP, appName) if transport == 'TLS': session_config = SessionConfig(SessionConfig.SessionTransportMode.TLS) session_config.ca_certs = cert ne.connect(user, pswd, session_config) elif transport == 'TIPC': session_config = SessionConfig(SessionConfig.SessionTransportMode.TIPC) ne.connect(user, pswd, session_config) else: print "Please set-up a valid transport type: TIPC or TLS" exit(0) vty = VtyService(ne) vty.open() vlan_summary = vty.write("sh vlan summary") vty.close() vlan_sum = re.search('(?<=vlansum-all-vlan\t)(.*)',vlan_summary) if int(vlan_sum.group(0)) > int(scale_limits["max_vlans"]): string_print = "Vlan scale exceeded. Max vlan recommended:",scale_limits["max_vlans"],"vlan being used :", vlan_sum.group(0) print string_print ne.create_syslog_message (ne.OnepSyslogSeverity.ONEP_SYSLOG_CRITICAL, str(string_print)); print "Disconnecting from NE: ",switchIP ne.disconnect()
def __init__(self, config, ne): """ Constructor Keyword argument: config The SessionConfig object whose attributes will be used and contained by this SessionProperty instance. ne The network element """ self.sessionConfig = SessionConfig(config) self.username = ne.username self.element = ne
parser.add_option('-p', '--password', dest="password", help="[Mandatory] Account Password for Login") (options, args) = parser.parse_args() if not options.ip: parser.print_help() parser.error("Provide IP Address") if not options.userName: parser.print_help() parser.error("Provide UserName") if not options.password: options.password = getpassword("Password:") # Setup a connection config with TLS pinning handler config = SessionConfig(None) config.set_tls_pinning('', PinningHandler('')) config.transportMode = SessionConfig.SessionTransportMode.TLS # Connection to my onePK enabled Network Element ne = NetworkElement(options.ip, 'App_Name') ne.connect(options.userName, options.password, config) # Print the information of the Network Element print ne # Finally have the application disconnect from the Network Element ne.disconnect()
# transport= 'TLS' cert = '<path>/cacert.pem' appName = "intf_properties_cn" switchIP = "<ip>" user = "******" pswd = "<pswd>" ##################################################################### # # Set up session connection configuration and connect to the switch # ne = NetworkElement(switchIP, appName) if transport == 'TLS': session_config = SessionConfig(SessionConfig.SessionTransportMode.TLS) session_config.ca_certs = cert ne.connect(user, pswd, session_config) elif transport == 'TIPC': session_config = SessionConfig(SessionConfig.SessionTransportMode.TIPC) ne.connect(user, pswd, session_config) else: print "Please set-up a valid transport type: TIPC or TLS" exit(0) RX_BYTES = InterfaceStatistics.InterfaceStatisticsParameter.ONEP_IF_STAT_RX_BYTES FILTER = InterfaceFilter(None, NetworkInterface.InterfaceTypes.ONEP_IF_TYPE_ETHERNET) print "Getting Interface Statistics on", switchIP
# cert - certificate to be used for authentication in cse of TLS # transport # appName - OnePK application Name # switchIP - management Switch IP address # user - switch userID pswd = "<pswd>" logMsg = "syslog generated by onePK" ##################################################################### # # Set up session connection configuration and connect to the switch # ne = NetworkElement(switchIP, appName) if transport == 'TLS': session_config = SessionConfig(SessionConfig.SessionTransportMode.TLS) session_config.ca_certs = cert ne.connect(user, pswd, session_config) elif transport == 'TIPC': session_config = SessionConfig(SessionConfig.SessionTransportMode.TIPC) ne.connect(user, pswd) else: print "Please set-up a valid transport type: TIPC or TLS" exit(0) # # Create the syslog messange and disconnect from the device # print "Generating Syslog message." ne.create_syslog_message(ne.OnepSyslogSeverity.ONEP_SYSLOG_CRITICAL, logMsg) print "Check on switch logs using \"sh log log duration 00:05:00\" cli"
help="[Mandatory] Account Username for Login") parser.add_option('-p', '--password',dest="password", help="[Mandatory] Account Password for Login") (options, args) = parser.parse_args() if not options.ip: parser.print_help() parser.error("Provide IP Address") if not options.userName: parser.print_help() parser.error("Provide UserName") if not options.password: options.password=getpassword("Password:") # Setup a connection config with TLS pinning handler config = SessionConfig(None) config.set_tls_pinning('', PinningHandler('')) config.transportMode = SessionConfig.SessionTransportMode.TLS # Connection to my onePK enabled Network Element ne = NetworkElement(options.ip, 'App_Name') ne.connect(options.userName, options.password, config) # Print the information of the Network Element print ne # Finally have the application disconnect from the Network Element ne.disconnect()