def delete_vxlan(self, vxlanid): xmldata = """ <config xmlns:xc="urn:ietf:params:xml:ns:netconf:base:1.0"> <top xmlns="http://www.h3c.com/netconf/config:1.0"> <VXLAN xc:operation="delete"> <VXLANs> <Vxlan> <VxlanID>""" + str( vxlanid) + """</VxlanID> </Vxlan> </VXLANs> </VXLAN> </top> </config> """ try: with manager.connect_ssh(host=self._server_ip, port=self._server_port, username=self._username, password=self._password, unknown_host_cb=self._my_unknown_host_cb, device_params={'name': 'h3c'}) as m: m.edit_config(target='running', config=xmldata) except Exception as e: LOG.error(e)
def get_iface_index(self, interface_name): ifindex = -1 xmldata = """ <top xmlns="http://www.h3c.com/netconf/data:1.0"> <Ifmgr> <Interfaces> <Interface> <IfIndex/> <Name>""" + interface_name + """</Name> <AbbreviatedName/> </Interface> </Interfaces> </Ifmgr> </top> """ try: with manager.connect_ssh(host=self._server_ip, port=self._server_port, username=self._username, password=self._password, unknown_host_cb=self._my_unknown_host_cb, device_params={'name': 'h3c'}) as m: c = m.get(('subtree', xmldata)).data_xml dom = xml.dom.minidom.parseString(str(c)) root = dom.documentElement ifIndex = root.getElementsByTagName("IfIndex") if len(ifIndex) != 0: ifindex = int(ifIndex[0].firstChild.data) except Exception as e: LOG.error(e) return ifindex
def create_tunnel(self, srcip, dstip, tunnelid): xmldata = """ <config xmlns="urn:ietf:params:xml:ns:netconf:base:1.0"> <top xmlns="http://www.h3c.com/netconf/config:1.0"> <TUNNEL> <Tunnels> <Tunnel> <ID>""" + str(tunnelid) + """</ID> <Mode>24</Mode> <IPv4Addr> <SrcAddr>""" + str(srcip) + """</SrcAddr> <DstAddr>""" + str(dstip) + """</DstAddr> </IPv4Addr> </Tunnel> </Tunnels> </TUNNEL> </top> </config> """ try: with manager.connect_ssh(host=self._server_ip, port=self._server_port, username=self._username, password=self._password, unknown_host_cb=self._my_unknown_host_cb, device_params={'name': 'h3c'}) as m: m.edit_config(target='running', config=xmldata) except Exception as e: LOG.error(e)
def get_srv_config(self, ifIndex): c = "" xmldata = """ <filter type="subtree"> <top xmlns="http://www.h3c.com/netconf/config:1.0"> <L2VPN> <SRVs> <SRV> <IfIndex>""" + str(ifIndex) + """</IfIndex> </SRV> </SRVs> </L2VPN> </top> </filter> """ try: with manager.connect_ssh(host=self._server_ip, port=self._server_port, username=self._username, password=self._password, unknown_host_cb=self._my_unknown_host_cb, device_params={'name': 'h3c'}) as m: c = m.get_config(source='running', filter=xmldata).data_xml except Exception as e: LOG.error(e) return c
def create_srv(self, ifIndex, srvID, sVlanRange, vsiName): xmldata = """ <config xmlns="urn:ietf:params:xml:ns:netconf:base:1.0"> <top xmlns="http://www.h3c.com/netconf/config:1.0"> <L2VPN> <SRVs> <SRV> <IfIndex>""" + str(ifIndex) + """</IfIndex> <SrvID>""" + str(srvID) + """</SrvID> <Encap>4</Encap> <SVlanRange>""" + str( sVlanRange) + """</SVlanRange> </SRV> </SRVs> <ACs> <AC> <IfIndex>""" + str(ifIndex) + """</IfIndex> <SrvID>""" + str(srvID) + """</SrvID> <VsiName>""" + str(vsiName) + """</VsiName> </AC> </ACs> </L2VPN> </top> </config> """ try: with manager.connect_ssh(host=self._server_ip, port=self._server_port, username=self._username, password=self._password, unknown_host_cb=self._my_unknown_host_cb, device_params={'name': 'h3c'}) as m: m.edit_config(target='running', config=xmldata) except Exception as e: LOG.error(e)
def delete_tunnel(self, tunnelid): if tunnelid == -1: return xmldata = """ <config xmlns:xc="urn:ietf:params:xml:ns:netconf:base:1.0"> <top xmlns="http://www.h3c.com/netconf/config:1.0"> <TUNNEL xc:operation="delete"> <Tunnels> <Tunnel> <ID>""" + str(tunnelid) + """</ID> </Tunnel> </Tunnels> </TUNNEL> </top> </config> """ try: with manager.connect_ssh(host=self._server_ip, port=self._server_port, username=self._username, password=self._password, unknown_host_cb=self._my_unknown_host_cb, device_params={'name': 'h3c'}) as m: m.edit_config(target='running', config=xmldata) except Exception as e: LOG.error(e)
def get_srv_id(self, ifIndex, sVlanRange): ifindex = -1 xmldata = """ <filter type="subtree"> <top xmlns="http://www.h3c.com/netconf/config:1.0"> <L2VPN> <SRVs> <SRV> <IfIndex>""" + str( ifIndex) + """</IfIndex> <SVlanRange>""" + str( sVlanRange) + """</SVlanRange> </SRV> </SRVs> </L2VPN> </top> </filter> """ try: with manager.connect_ssh(host=self._server_ip, port=self._server_port, username=self._username, password=self._password, unknown_host_cb=self._my_unknown_host_cb, device_params={'name': 'h3c'}) as m: c = m.get_config(source='running', filter=xmldata).data_xml dom = xml.dom.minidom.parseString(str(c)) root = dom.documentElement ifIndex = root.getElementsByTagName("SrvID") if len(ifIndex) != 0: ifindex = int(ifIndex[0].firstChild.data) except Exception as e: LOG.error(e) return ifindex
def delete_srv(self, ifIndex, sVlanRange): srvID = self.get_srv_id(ifIndex=ifIndex, sVlanRange=sVlanRange) if srvID == -1: return xmldata = """ <config xmlns:xc="urn:ietf:params:xml:ns:netconf:base:1.0"> <top xmlns="http://www.h3c.com/netconf/config:1.0"> <L2VPN xc:operation="delete"> <ACs> <AC> <IfIndex>""" + str(ifIndex) + """</IfIndex> <SrvID>""" + str(srvID) + """</SrvID> </AC> </ACs> <SRVs> <SRV> <IfIndex>""" + str(ifIndex) + """</IfIndex> <SrvID>""" + str(srvID) + """</SrvID> </SRV> </SRVs> </L2VPN> </top> </config> """ try: with manager.connect_ssh(host=self._server_ip, port=self._server_port, username=self._username, password=self._password, unknown_host_cb=self._my_unknown_host_cb, device_params={'name': 'h3c'}) as m: m.edit_config(target='running', config=xmldata) except Exception as e: LOG.error(e)
def main(): device_params=None if aargs.devicetype in ['j','c','n','h','junos','csr','nexus','huawei']: device_params={'name':aargs.devicetype} if len(aargs.devicetype)>1 else None device_params={'name':'junos'} if not device_params and aargs.devicetype=='j' else None device_params={'name':'csr'} if not device_params and aargs.devicetype=='c' else None device_params={'name':'nexus'} if not device_params and aargs.devicetype=='n' else None device_params={'name':'huawei'} if not device_params and aargs.devicetype=='h' else None ### READ YAML NETCONF AUTH FILE ---------------------------------------------- with open('./netconf_auth_data.yaml', 'r') as stream: netconf_auth_data = yaml.load(stream) if netconf_auth_data: with manager.connect_ssh(host=netconf_auth_data.get('netconf_ipaddress'), port=netconf_auth_data.get('netconf_ssh_port'), username=netconf_auth_data.get('netconf_user'), password=netconf_auth_data.get('netconf_password'), device_params=device_params, hostkey_verify=False ) as m: if aargs.verbose: print('CONNECTED:',m.connected,'\nCAPABILITIES:') for c in m.server_capabilities: print(c) ### GET RUNNING CONFIG ================================================= if aargs.getrunningconfig: running_config = m.get_config('running').data_xml if aargs.verbose: print('\nRUNNING_CONFIG:\n',xml.dom.minidom.parseString(str(running_config)).toprettyxml()) now = datetime.datetime.now() timestring='%04d%02d%02d_%02d%02d%02d'%(now.year,now.month,now.day,now.hour,now.minute,now.second) file_name='running_config_'+timestring+'.xml' with open(file_name, 'w', encoding='utf8') as outfile: outfile.write(xml.dom.minidom.parseString(str(running_config)).toprettyxml()) print('Writing running-config to file:',file_name) #exit(0) if aargs.comparewithfile: diff = xdmain.diff_files(aargs.comparewithfile, file_name, formatter=formatting.XMLFormatter()) print(diff)
def demo(host, port, user, pwd): with manager.connect_ssh(host=host, port=port, username=user, password=pwd, unknown_host_cb=my_unknown_host_cb, device_params={'name': 'h3c'}) as m: xml = """ <config xmlns="urn:ietf:params:xml:ns:netconf:base:1.0"> <top xmlns="http://www.h3c.com/netconf/config:1.0"> <L2VPN> <SRVs> <SRV> <IfIndex>4</IfIndex> <SrvID>1</SrvID> <Encap>4</Encap> <SVlanRange>1234</SVlanRange> </SRV> </SRVs> <ACs> <AC> <IfIndex>4</IfIndex> <SrvID>1</SrvID> <VsiName>vpna</VsiName> </AC> </ACs> </L2VPN> </top> </config> """ print m.edit_config(target='running', config=xml)
def connect(self): '''Returns True if connect to device is successful.''' self.handle = manager.connect_ssh(self.hostname, username=self.username, password=self.password, port=self.port, hostkey_verify=False)
def connect_switch(self): """ Connect switch. Arguments: host : IP address. port : Valid Port No. username : Valid User Name. password : Valid password. timeout : valid switch timeout with sec """ global sw_mgr host = get_config_arg("login_credentials", "host") port = get_config_arg("login_credentials", "port") username = get_config_arg("login_credentials", "user_name") password = get_config_arg("login_credentials", "password") timeout = get_config_arg("login_credentials", "timeout") LOG.info('connecting switch <IP:Port = %s:%s>\n' % (host, port)) sw_mgr = manager.connect_ssh( host=host, port=port, username=username, password=password, timeout=int(timeout), hostkey_verify=False)
def get_capabilities(args): print( '-----------------------------------------------------------------------------------------------------------------' ) print( '---------------------------------------------SERVER CAPABILITIES-------------------------------------------------' ) print( '-----------------------------------------------------------------------------------------------------------------' ) with manager.connect_ssh(host=args.host, port=args.port, username=args.username, hostkey_verify=False, password=args.password) as m: for cap in m.server_capabilities: print(cap) print( '-----------------------------------------------------------------------------------------------------------------' ) print( '---------------------------------------------SERVER CAPABILITIES-------------------------------------------------' ) print( '-----------------------------------------------------------------------------------------------------------------' )
def __init__(self, ip, port=22, username="******", password="******"): self._m = None self.mainDevice = {} self.devices = [] self.connected = None self.status = False self.errorinfo = "" self.ip = ip self.port = port self.username = username self.password = password self.mainDevice["ip"] = self.ip self.mainDevice["port"] = self.port self.mainDevice["username"] = self.username self.mainDevice["passwd"] = self.password # manager.logging.basicConfig(filename='e:/ncclient.log', level=manager.logging.DEBUG) logger.debug("client session request initiated ") try: self._m = manager.connect_ssh( ip, port=port, username=username, password=password, allow_agent=False, look_for_keys=False ) self.status = self._m.connected logger.debug("client session creation is successful ") except Exception as e: self.status = False self.errorinfo = e logger.error("client session creation is failed. error: %s ", self.errorinfo)
def testconnectSwitch(host, port, userName, password, timeout): ### Connecting to switch ### global swMgr logger.info("Connecting to switch <IP:Port = %s:%s>\n" % (host,port)) swMgr = manager.connect_ssh(host=host, port=port, username=userName, password=password,timeout=timeout, hostkey_verify=False) logger.info('swMgr is : %s' % swMgr)
def open( self, hostname: Optional[str], username: Optional[str], password: Optional[str], port: Optional[int], platform: Optional[str], extras: Optional[Dict[str, Any]] = None, configuration: Optional[Config] = None, ) -> None: extras = extras or {} parameters: Dict[str, Any] = { "host": hostname, "username": username, "password": password, "port": port or 830, } if "ssh_config" not in extras: try: ssh_config_file = Path( configuration.ssh.config_file) # type: ignore if ssh_config_file.exists(): parameters["ssh_config"] = ssh_config_file except AttributeError: pass parameters.update(extras) connection = manager.connect_ssh(**parameters) self.connection = connection
def main(): if xmlfile is not None: try: with open(xmlfile, 'r') as input: xml = input.read().replace('\n', '') except: print("Couldn't read XML file %s" % xmlfile) exit(1) if args.l: manager.logging.basicConfig(filename='ncclient.log', level=manager.logging.DEBUG) with manager.connect_ssh(host=host, port=port, username=user, password=password, hostkey_verify=False, device_params={'name': devtype}, timeout=timeout) as m: if command == 'push': m.edit_config(target=target, config=xml, default_operation='merge') elif command == 'get': if xmlfile is not None: output = m.get_config(source=target, filter=xml) else: output = m.get_config(source=target) print(output)
def pushconfig(self, config): print ("Applique configuration: %s - %s - %s" % (self.hostname, self.ipaddress, self.model)) xmlstr = netconfXML.get_xml(config) print (xmlstr) m = manager.connect_ssh(self.ipaddress, port=22, username='******', password='******', device_params={'name': 'csr'}) m.edit_config(target='running', config=xmlstr) m.copy_config(target='startup', source='running')
def getCapabilities(host, port, userName, password, timeout): print "Connecting to switch <IP:Port = %s:%s>\n" % (host,port) swMgr = manager.connect_ssh(host=host, port=port, username=userName, password=password,timeout=timeout, hostkey_verify=False) print "The capabilities advertised by Switch are:\n" for c in swMgr.server_capabilities: print c
def establish_manager_connection(): global m try: m = manager.connect_ssh(target_ip, port=target_port, username=target_username, password=target_password, allow_agent=False, hostkey_verify=False, look_for_keys=False) get_device_dict() except socket_error as serr: set_script_error( 'socket_error exception in establish_manager_connection(). ' + 'Maybe unable to open socket. ' + 'Log: ' + str(serr)) print( "establish_manager_connection(): Error socket_error couldnt open") print(serr) except Exception as e: set_script_error('exception in establish_manager_connection(). ' + 'Log: ' + str(e)) print( "establish_manager_connection(): Exception something else not caught by socket_error" ) print(e)
def executeCommands(self, command): m = manager.connect_ssh(self.mgmtip, username=self.username, password=self.password, port=self.__ncport, hostkey_verify=False) c = m.get_config(source='running').data_xml conf_dict = {"dns_ip":self.Dnslocalip , "private_ip": self.localip , "public_ip": self.publicip, "chronos_ip": self.localip} confstr = template.allnode_settings.format(**conf_dict) c1 = m.edit_config(target='candidate', config=confstr) m.commit()
def __init__(self, ip, port=22, username="******", password="******"): self._m = None self.mainDevice = {} self.devices = [] self.connected = None self.status = False self.errorinfo = '' self.ip = ip self.port = port self.username = username self.password = password self.mainDevice['ip'] = self.ip self.mainDevice['port'] = self.port self.mainDevice['username'] = self.username self.mainDevice['passwd'] = self.password #manager.logging.basicConfig(filename='e:/ncclient.log', level=manager.logging.DEBUG) logger.debug('client session request initiated ') try: self._m = manager.connect_ssh(ip, port=port, username=username, password=password, allow_agent=False, look_for_keys=False) self.status = self._m.connected logger.debug('client session creation is successful ') except Exception as e: self.status = False self.errorinfo = e logger.error('client session creation is failed. error: %s ', self.errorinfo)
def get_device_type(nhost, nport, nusername, npassword): device_type = None with manager.connect_ssh(host=nhost, port=nport, username=nusername, password=npassword, device_params=None, timeout=10, allow_agent=False, look_for_keys=False, hostkey_verify=False) as m: if aargs.verbose: print('CAPABILITIES:', list(m.server_capabilities)) for c in m.server_capabilities: #if 'TAILF-NCS' in c.upper(): device_type='nso'; break; if 'JUNIPER' in c.upper(): device_type = 'junos' break if 'NX-OS' in c.upper(): device_type = 'nexus' break if 'Cisco-IOS-XR' in c: device_type = 'csr' break if 'HUAWEI' in c.upper(): device_type = 'huawei' break print('DEVICE_TYPE:', device_type) return device_type
def demo(host, port, user, pwd): with manager.connect_ssh(host=host, port=port, username=user, password=pwd, unknown_host_cb=my_unknown_host_cb, device_params={'name': 'h3c'}) as m: xml = """ <config xmlns="urn:ietf:params:xml:ns:netconf:base:1.0"> <top xmlns="http://www.h3c.com/netconf/config:1.0"> <TUNNEL> <Tunnels> <Tunnel> <ID>2</ID> <Mode>24</Mode> <IPv4Addr> <SrcAddr>11.11.11.11</SrcAddr> <DstAddr>4.4.4.4</DstAddr> </IPv4Addr> </Tunnel> </Tunnels> </TUNNEL> </top> </config> """ print m.edit_config(target='running', config=xml)
def send_command(self, device_name, command_list): if not self.handle(device_name): return False name, ip, port, login, password, syntaxe = self.device_data[:6] if syntaxe + '.stx' not in os.listdir(self.syntaxe): LOG.error(_("Error, this syntax is unknown")) return False if not os.path.isfile(self.syntaxe + '/' + syntaxe + '.stx'): LOG.error(_("Error, syntaxe file, %s%s.stx is not a file ..."), self.syntaxe, syntaxe) return False syntaxe_fd = open(self.syntaxe + '/' + syntaxe + '.stx') syntax_dict = eval(syntaxe_fd.readline()) try: with manager.connect_ssh(ip, port=port, username=login, password=password, unknown_host_cb=unknown_host_cb, look_for_keys=False) as m: #template = """<config xmlns:xc="urn:ietf:params:xml:ns:netconf:base:1.0"><aaa xmlns="http://tail-f.com/ns/aaa/1.1"><authentication> <users> <user xc:operation="delete"><name>%s</name></user></users></authentication></aaa></config>""" #ip_change = """<config xmlns:xc="urn:ietf:params:xml:ns:netconf:base:1.0"> #<cpi:xml-config-data xmlns:cpi="http://www.cisco.com/cpi_10/schema"><Hostname>R1</Hostname><Interface><InterfaceName>fastEthernet0/1</InterfaceName><IP><Address><IPAddress>192.168.1.1</IPAddress><Mask>255.255.255.0</Mask></Address></IP></Interface></cpi:xml-config-data></config>""" #hostname = """<config xmlns:xc="urn:ietf:params:xml:ns:netconf:base:1.0"><cpi:cli_driver-config-data-block>username nectonfCreated</cpi:cli_driver-config-data-block></config>""" #hostname2 = """<config><cli_driver-config-data><cmd>username clement</cmd></cli_driver-config-data></config>""" cmd_list = '' for command in command_list: cmd_list += syntax_dict['command'] % command conf_patch = syntax_dict['wrapper'] % cmd_list with m.locked(target='running'): m.edit_config(target='running', config=conf_patch) return True except sshErr.SSHError as e: raise map_utils.DriverFails(str(e))
def connectSwitch(host, port, userName, password, timeout): ### connecting to the switch ### global swMgr logger.info("connecting ot switch <IP:port = %s:%s>\n" % (host, port)) swMgr = manager.connect_ssh( host=host, port=port, username=userName, password=password, timeout=timeout, hostkey_verify=False )
def connect_mgr(): return connect_ssh( host="localhost", port=830, username="******", password="******", hostkey_verify=False, )
def createSAs(registered_node, star=False): control_address = registered_nodes[registered_node][0] # in star topology if (star and registered_node > 0): netconf_sessions[control_address] = manager.connect_ssh( host=control_address, port=830, timeout=60, username="******", password=None, key_filename=None, allow_agent=True, hostkey_verify=True, look_for_keys=True, ssh_config=None) if netconf_sessions[control_address] is not None: # set up of TLS associations between all stable nodes # if registered_node > 0: if star: servers = [registered_nodes[0][1]] else: servers = [] for server in range(0, registered_node, 1): servers.append(registered_nodes[server][1]) # XML client_configuration = "<config xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">" i = 0 for server in servers: i = i + 1 client_conf = configuration_model client_conf = client_conf.replace("SA-ID", str(i)) client_conf = client_conf.replace("SERVER-ADDRESS", server) if i == len(servers) or i == 1: client_conf = client_conf.replace( "LAST-NSF-FLAG", "true") else: client_conf = client_conf.replace( "LAST-NSF-FLAG", "false") client_conf = client_conf.replace( "CLIENT-CERT", node_certs[control_address]) client_configuration = client_configuration + client_conf client_configuration = client_configuration + "</config>" # edit config netconf_sessions[control_address].edit_config( target='running', config=client_configuration, test_option='test-then-set') # new node completely configured netconf_sessions[control_address].close_session()
def connect_mgr(): return connect_ssh( host="localhost", port=830, username="******", password="******", hostkey_verify=False, timeout=180, )
def test_connect_ssh2(self, mock_session, mock_hex, mock_trans, mock_socket): conn = manager.connect_ssh(host='10.10.10.10', port=22, username='******', password='******', timeout=3, hostkey_verify=False, allow_agent=False, keepalive=10) self.assertEqual(mock_trans.called, 1)
def losClearOp(host, port, userName, password, timeout): print "Connecting to switch <IP:Port = %s:%s>\n" % (host,port) swMgr = manager.connect_ssh(host=host, port=port, username=userName, password=password,timeout=timeout, hostkey_verify=False) losClear="""<config xmlns:xc="urn:ietf:params:xml:ns:netconf:base:1.0"><ports xmlns="http://www.polatis.com/yang/optical-switch"><port><port-id>3</port-id><port-label/><port-state>PC_ENABLED</port-state><opm><lambda>1550.0</lambda><power-high-alarm>25.0</power-high-alarm><power-low-alarm>-60.0</power-low-alarm><power-high-warning-offset>25.0</power-high-warning-offset><power-low-warning-offset>0.0</power-low-warning-offset><power-alarm-control>POWER_ALARM_DISABLED</power-alarm-control><offset xmlns="http://www.polatis.com/yang/polatis-switch">10.0</offset><averaging-time-select xmlns="http://www.polatis.com/yang/polatis-switch">4</averaging-time-select><power-alarm-hysteresis xmlns="http://www.polatis.com/yang/polatis-switch">1.0</power-alarm-hysteresis><power-alarm-clear-holdoff xmlns="http://www.polatis.com/yang/polatis-switch">60</power-alarm-clear-holdoff></opm></port></ports>""" try: print "Issuing edit config to switch for los alarm configuration\n" swMgr.edit_config(target='running', config=losClear ) except: print "Error:"
def gather_juniper_metrics(juniper_host, user, password, port, prefix): """ Connects to a Juniper via NetConf and pulls statistics. """ metric_list = [] try: logging.info("Connecting to %s and pulling statistics..." % juniper_host) j = manager.connect_ssh(juniper_host, username=user, password=password, port=port) except Exception, detail: logging.debug("detail = %s" % pformat(detail)) pass
def write_config(args, d_config): if args.capabilities: get_capabilities(args) with manager.connect_ssh(host=args.host, port=args.port, username=args.username, hostkey_verify=False, password=args.password) as m: try: c = m.edit_config(d_config, target='running') except Exception as e: print('Failed to execute <edit-config> RPC: {}'.format(e))
def __init__(self, host, username, password): self.host = host self.username = username self.password = password try: self.conn = manager.connect_ssh(host = self.host, username = self.username, password = self.password, hostkey_verify = False, look_for_keys=False) except: self.conn = None raise ValueError("Tor Connection Init Failed.")
def main(): ### TESTSTRINGS # l1=[('SINPE55', 'ge-1/0/2.0', 'Up'), ('PASCR6', 'so-0/0/0.1', 'Up'), ('LONCR1', 'so-0/2/0.0', 'Up'), ('PASCR7', 'xe-1/2/1.0', 'Up'), ('SINCR4', 'xe-1/2/3.0', 'Up'), ('PASCR7', 'xe-1/2/4.0', 'Up'), ('SINCR4', 'xe-2/2/2.0', 'Up'), ('SINPE4', 'xe-2/2/3.0', 'Up'), ('PASCR7', 'xe-2/2/4.0', 'Up'), ('SINCR4', 'xe-2/2/5.0', 'Up')] # l2=[('SINPE5', 'ge-1/0/2.0', 'Up'), ('PASCR6', 'so-0/0/0.0', 'Up'), ('LONCR1', 'so-0/2/0.0', 'Up'), ('PASCR7', 'xe-1/2/1.0', 'Down'), ('SINCR4', 'xe-1/2/3.0', 'Up'), ('PASCR7', 'xe-1/2/4.0', 'Up'), ('SINCR4', 'xe-2/2/2.0', 'Up'), ('SINPE4', 'xe-2/2/3.0', 'Up'), ('PASCR7', 'xe-2/2/4.0', 'Up'), ('SINCR4', 'xe-2/2/5.0', 'Up')] # get_string_file_difference_string(l1,l2) # exit(0) file_name=str() device_params=None netconf_auth_data=None if aargs.devicetype in ['j','c','n','h','junos','csr','nexus','huawei']: device_params={'name':aargs.devicetype} if len(aargs.devicetype)>1 else None device_params={'name':'junos'} if not device_params and aargs.devicetype=='j' else None device_params={'name':'csr'} if not device_params and aargs.devicetype=='c' else None device_params={'name':'nexus'} if not device_params and aargs.devicetype=='n' else None device_params={'name':'huawei'} if not device_params and aargs.devicetype=='h' else None device_params={'name': 'default'} if not device_params else {'name': 'default'} ### AUTHORIZATION - READ YAML NETCONF AUTH FILE OR INPUT PARAMETERS----------- if aargs.yamlauthfile: with open(aargs.yamlauthfile, 'r') as stream: netconf_auth_data = yaml.load(stream) if not netconf_auth_data: netconf_auth_data = yaml.load(netconf_auth_data_yaml) nhost=netconf_auth_data.get('netconf_ipaddress','') nport=netconf_auth_data.get('netconf_ssh_port','') nusername=netconf_auth_data.get('netconf_user','') npassword=netconf_auth_data.get('netconf_password','') ### OVERDIDE/INSERT INPUT PARAMETERS ----------------------------------------- if aargs.netconfusername: nusername=aargs.netconfusername if aargs.netconfpassword: npassword=aargs.netconfpassword if aargs.netconfaddress: nhost=aargs.netconfaddress if aargs.netconfport: nport=aargs.netconfport ### NETCONF CONNECT ---------------------------------------------------------- print('HOST:',nhost,', PORT:',nport,', USER:'******', PASSWORD:'******'YES' if npassword else '-') if nhost and nport and nusername and npassword: recognised_dev_type=get_device_type(nhost,nport,nusername,npassword) if not aargs.devicetype and recognised_dev_type: device_params={'name':recognised_dev_type} with manager.connect_ssh(host=nhost,port=nport,username=nusername,password=npassword, device_params=device_params,timeout=30,allow_agent=False, look_for_keys=False,hostkey_verify=False ) as m: print('CONNECTED :',m.connected) get_junos_productmodel_and_osversion(m,recognised_dev_type) if aargs.getcapabilities: ncclient_capabilities_to_file(m,recognised_dev_type) if aargs.getrpc: file_name=ncclient_rpc_to_file(m,recognised_dev_type) if aargs.getdata: file_name=ncclient_get_to_file(m,recognised_dev_type) if aargs.getrunningconfig or aargs.getcandidateconfig: file_name=ncclient_getconfig_to_file(m,recognised_dev_type) if aargs.getcommands: file_name=ncclient_commands_to_file(m,recognised_dev_type) if not file_name: file_name=ncclient_read_all(m,recognised_dev_type) if aargs.comparewithfile: compare_xml_files_and_do_diff_file(file_name,aargs.comparewithfile,recognised_dev_type) ### -------------------------------------------------------------------------- if aargs.verbose and aargs.xpathexpression: print('\nDEBUG_XPATH to XML:\n'+get_xmlstring_from_xpath(aargs.xpathexpression))
def getStaticData(host, port, userName, password, timeout,outFileName,expr): print "Connecting to switch <IP:Port = %s:%s>\n" % (host,port) swMgr = manager.connect_ssh(host=host, port=port, username=userName, password=password,timeout=timeout, hostkey_verify=False) try: print "quering both configuration and static data from switch using get operation\n"; if expr is not None: xmlData = swMgr.get(filter=('xpath',expr)).data_xml else: xmlData = swMgr.get-config().data_xml writeToFile(outFileName,xmlData); except: print "Error:"
def crossConnectOp(host, port, userName, password, timeout,operation, ingressPort, egressPort): print "Connecting to switch <IP:Port = %s:%s>\n" % (host,port) swMgr = manager.connect_ssh(host=host, port=port, username=userName, password=password,timeout=timeout, hostkey_verify=False) opStr='' if operation == 'del': opStr = "ns:operation=\"delete\"" crossConnectStr="""<config xmlns:xc="urn:ietf:params:xml:ns:netconf:base:1.0"><cross-connects xmlns="http://www.polatis.com/yang/optical-switch"><pairs %s><ingress>%s</ingress><egress>%s</egress></pairs></cross-connects></config>""" %(opStr,ingressPort, egressPort) try: print "Issuing edit config to switch for cross-connect configuration\n" swMgr.edit_config(target='running', config=crossConnectStr ) except: print "Error:"
def uninstall_route(self): with manager.connect_ssh(self.config["rtrA"]["hostname"], username=self.config["rtrA"]["username"], password=self.config["rtrA"]["password"], hostkey_verify=False) as m: with m.locked("running"): m.edit_config(target="running", config=""" <nc:config xmlns:nc="urn:ietf:params:xml:ns:netconf:base:1.0"> <srv6-explicit-path xmlns="urn:ietf:params:xml:ns:yang:srv6-explicit-path"> <path nc:operation="delete"> <destination>2222:4::2</destination> </path> </srv6-explicit-path> </nc:config>""")
def connect_switch(self, host, port, userName, password, timeout): """ Connect switch. Arguments: host : IP address. port : Valid Port No. username : Valid User Name. password : Valid password. timeout : valid switch timeout with sec """ global sw_mgr LOG.info("Connecting to switch <IP:Port = %s:%s>\n" % (host,port)) sw_mgr = manager.connect_ssh(host=host, port=port, username=userName, password=password,timeout=timeout, hostkey_verify=False)
def send_edit_config(host_ip, username, password): with manager.connect_ssh(host=host_ip, port=830, username=username, password=password, hostkey_verify=False ) as m: try: m.edit_config(target='running', config=nexthop_ucast_xml, default_operation='merge', error_option='stop-on-error') except Exception as e: print "Fail to edit-config config_nexthop_ucast_xml" return -1 try: m.edit_config(target='running', config=config_nexthop_mcast_xml, default_operation='merge', error_option='stop-on-error') except Exception as e: print "Fail to edit-config config_nexthop_mcast_xml" return -1 try: m.edit_config(target='running', config=config_vni_xml, default_operation='merge', error_option='stop-on-error') except Exception as e: print "Fail to edit-config config_vni_xml" return -1 try: m.edit_config(target='running', config=vtep_xml, default_operation='merge', error_option='stop-on-error') except Exception as e: print "Fail to edit-config vtep_xml" return -1 try: m.edit_config(target='running', config=vtap_xml, default_operation='merge', error_option='stop-on-error') except Exception as e: print "Fail to edit-config vtap_xml" return -1 print m.get_config(source='running').data_xml
def getConfigPort(host, port, userName, password, timeout,outFileName, expr): print "Connecting to switch <IP:Port = %s:%s>\n" % (host,port) swMgr = manager.connect_ssh(host=host, port=port, username=userName, password=password,timeout=timeout, hostkey_verify=False) try: print "Quering for running configuration data from switch using get_config\n" if expr is not None: xmlData = swMgr.get_config(source='running', filter=('xpath',expr)).data_xml else: xmlData = swMgr.get_config(source='running').data_xml writeToFile(outFileName,xmlData); except: print "Error:"
def get_config(args, x_filter): if args.capabilities: get_capabilities(args) with manager.connect_ssh(host=args.host, port=args.port, username=args.username, hostkey_verify=False, password=args.password) as m: try: c = m.get(x_filter) #c = m.get_config("running", x_filter) except Exception as e: print('Failed to execute <get> RPC: {}'.format(e)) received_config = xml.dom.minidom.parseString(c.data_xml).toprettyxml() return received_config
def demo(host, port, user, pwd): with manager.connect_ssh(host=host, port=port, username=user, password=pwd, unknown_host_cb=my_unknown_host_cb, device_params = {'name':'h3c'}) as m: xml = """ <filter type="subtree"> <top xmlns="http://www.h3c.com/netconf/config:1.0"> <L2VPN></L2VPN> <VXLAN></VXLAN> <TUNNEL></TUNNEL> </top> </filter> """ print m.get_config(source='running').data_xml
def initialize(self, mgr, user, passwd): self.mgr, self.user, self.passwd = mgr, user, passwd if self.mgr not in self.conn: self.conn[mgr] = None now = time.time() expired = int(now - self.timestamp) if not self.conn[self.mgr] or expired > 30: try: self.conn[self.mgr] = manager.connect_ssh(host = self.mgr, username = self.user, password = self.passwd, hostkey_verify = False, look_for_keys=False) self.timestamp = time.time() except Exception as e: print str(e) return False return True
def _handle_connect(self, **creds): """ Initiate a persistent ssh connection, in the worker thread """ kwargs = {'username': creds['username'], 'port': creds.get('netconf_port', 830), 'device_params': {'name':'iosxr'}} if 'ssh_key' in creds: kwargs['key_filename'] = creds['ssh_key'] else: kwargs['password'] = creds.get('password', '') try: self.mgr = nc_mgr.connect_ssh(creds['host'], **kwargs) self.mgr.raise_mode = RaiseMode.NONE self._update_state(ConState.FINALIZING) except Exception as e: self.mgr = None self._update_state(ConState.FAILED_TO_CONNECT, str(e))
def main(): if xmlfile is not None: try: with open(xmlfile, 'r') as input: xml = input.read().replace('\n', '') except: print("Couldn't read XML file %s" % xmlfile) exit(1) if args.l: manager.logging.basicConfig(filename='ncclient.log', level=manager.logging.DEBUG) with manager.connect_ssh(host=host, port=port, username=user, password=password, hostkey_verify=False, device_params={'name':devtype}, timeout=timeout) as m: if command == 'push': m.edit_config(target=target, config=xml, default_operation='merge') elif command == 'get': if xmlfile is not None: output = m.get_config(source=target, filter=xml) else: output = m.get_config(source=target) print(output)
</of11-config:capable-switch> </config> """ config_xml=""" <config> <of11-config:capable-switch xmlns:of11-config="urn:onf:of111:config:yang"> <ofdpa10:ecmp xmlns:ofdpa10="urn:bcm:ofdpa10:accton01"> <ofdpa10:id>10</ofdpa10:id> <ofdpa10:nexthop-id>10</ofdpa10:nexthop-id> </ofdpa10:ecmp> </of11-config:capable-switch> </config> """ with manager.connect_ssh(host=host, port=830, username=username, password=password, hostkey_verify=False ) as m: print "Create Next Group" print m.edit_config(target='running', config=config_next_hop_xml, default_operation='merge', error_option='stop-on-error') print "Create ECMP Group" print m.edit_config(target='running', config=config_xml, default_operation='merge', error_option='stop-on-error') print m.get_config(source='running').data_xml
def reconnect(self): """subdevices list must be there, loop to subdevices ,and try to connect each first succes connection will return """ # reconnect main device if self.getStatus() == False: try: self.ip = self.mainDevice["ip"] self.port = self.mainDevice["port"] self.username = self.mainDevice["username"] self.password = self.mainDevice["passwd"] self._m = manager.connect_ssh( self.ip, port=self.port, username=self.username, password=self.password, allow_agent=False, look_for_keys=False, ) if self._m is not None: self.status = self._m.connected logger.info( "Client session is created by ip:%s, port:%s, username:%s" % (self.ip, self.port, self.username) ) return self._m.connected except Exception as e: self.status = False self.errorinfo = e logger.debug( "client session creation failed. ip:%s, port:%s, username:%s error: %s ", self.ip, self.port, self.username, self.errorinfo, ) # logger.exception(e) goToNextDevice = True if self.getStatus() == False: if not self.devices: logger.debug("DeviceList is Empty") return None for subDevices in self.devices: goToNextDevice = True if not subDevices: logger.debug("No sub device present") return None for keys, values in subDevices.iteritems(): if not values: goToNextDevice = False logger.debug("Invalid or empty parameter") break try: self.ip = subDevices.get("ip") self.port = subDevices.get("port") self.username = subDevices.get("username") self.password = subDevices.get("passwd") connected = manager.connect_ssh( self.ip, port=self.port, username=self.username, password=self.password, allow_agent=False, look_for_keys=False, ) if connected is not None: self._m = connected logger.info( "Client session is created by ip:%s, port:%s, username:%s" % (self.ip, self.port, self.username) ) self.status = self._m.connected return self._m.connected except Exception as e: self.status = False self.errorinfo = e logger.debug( "client session creation failed. ip:%s, port:%s, username:%s, error: %s ", self.ip, self.port, self.username, self.errorinfo, ) # logger.exception(e) return None return None
""" oxc continuous test """ from ncclient import manager import time create_xmlstr = """<config xmlns:xc="urn:ietf:params:xml:ns:netconf:base:1.0"><cross-connects xmlns="http://www.polatis.com/yang/optical-switch"><pairs><ingress>1</ingress><egress>17</egress></pairs><pairs><ingress>2</ingress><egress>18</egress></pairs><pairs><ingress>3</ingress><egress>19</egress></pairs></cross-connects></config>""" delete_xmlstr = """<config xmlns:xc="urn:ietf:params:xml:ns:netconf:base:1.0"><cross-connects xmlns="http://www.polatis.com/yang/optical-switch"><pairs nc:operation = 'delete'><ingress>1</ingress><egress>17</egress></pairs><pairs nc:operation = 'delete'><ingress>2</ingress><egress>18</egress></pairs><pairs nc:operation = 'delete'><ingress>3</ingress><egress>19</egress></pairs></cross-connects></config>""" cnt = 1 with manager.connect_ssh(host = '10.99.99.227', port = '830', username = '******', password = '******', hostkey_verify=False) as m: while True: #print "m : %s\n" % m print "oxc create and delete operation : %s\n\n" % cnt print "-----[ create oxc ]-----\n" xml_output = m.edit_config(target='running', config=create_xmlstr) print '\n\n' print "Response from the switch : \n\n%s\n" % xml_output print '\n\n' print "waiting for 20 sec\n" time.sleep(20) print "-----[ delete oxc ]-----\n" xml_output = m.edit_config(target='running', config=delete_xmlstr) print '\n\n' print "Response from the switch : \n\n%s\n" % xml_output print '\n\n' print "waiting for 20 sec\n" time.sleep(20)