Beispiel #1
0
def _test_multi_open(client_cache):

    logger.info("Create Server")
    server_ctl = server.SSHUserPassController(username=getpass.getuser(),
                                              password="******")
    ns = server.NetconfSSHServer(server_ctl=server_ctl,
                                 server_methods=NetconfMethods(),
                                 port=NC_PORT,
                                 host_key="tests/host_key",
                                 debug=SERVER_DEBUG)
    port = ns.port

    logger.info("Open sessions")
    sessions = [
        client.NetconfSSHSession("127.0.0.1",
                                 password="******",
                                 port=port,
                                 debug=CLIENT_DEBUG,
                                 cache=client_cache)
        for unused in range(0, 25)
    ]

    logger.info("Close sessions")
    for session in sessions:
        session.close()

    logger.info("Reopening")
    sessions = [
        client.NetconfSSHSession("127.0.0.1",
                                 password="******",
                                 port=port,
                                 debug=CLIENT_DEBUG)
        for unused in range(0, 25)
    ]

    logger.info("Closeing")
    for session in sessions:
        session.close()

    logger.info("Reopening")
    sessions = [
        client.NetconfSSHSession("127.0.0.1",
                                 password="******",
                                 port=port,
                                 debug=CLIENT_DEBUG)
        for unused in range(0, 25)
    ]
    logger.info("Reclosing")
    for session in sessions:
        session.close()

    # Close down the server and join it to make sure it's closed
    logger.info("Closing server")
    ns.close()
    logger.info("Joining server")
    ns.join()

    # Delete the server so that we don't end up with a bunch of logging going on on exit.
    del ns
    del server_ctl
Beispiel #2
0
def test_server_close():
    server_ctl = server.SSHUserPassController(username=getpass.getuser(),
                                              password="******")
    port = None
    LAST_INDEX = 40000 + 5000
    for port in range(40000, LAST_INDEX + 1):
        try:
            logger.info("Create server on port %d", port)
            ns = server.NetconfSSHServer(server_ctl=server_ctl,
                                         server_methods=NetconfMethods(),
                                         port=port,
                                         host_key="tests/host_key",
                                         debug=SERVER_DEBUG)
            break
        except socket.error as error:
            logger.info("Got exception: %s %d %d", str(error), error.errno,
                        errno.EADDRINUSE)
            if error.errno != errno.EADDRINUSE or port == LAST_INDEX:
                raise

    logger.info("Connect to server on port %d", port)
    session = client.NetconfSSHSession("127.0.0.1",
                                       password="******",
                                       port=port,
                                       debug=CLIENT_DEBUG)
    session.close()
    # NetconfSSHSession.flush()

    logger.debug("Closing")
    ns.close()
    logger.debug("Joining")
    ns.join()

    # import time
    # time.sleep(.1)

    for i in range(0, 10):
        logger.debug("Starting %d iteration", i)
        ns = server.NetconfSSHServer(server_ctl=server_ctl,
                                     server_methods=NetconfMethods(),
                                     port=port,
                                     host_key="tests/host_key",
                                     debug=SERVER_DEBUG)

        logger.info("Connect to server on port %d", port)
        session = client.NetconfSSHSession("127.0.0.1",
                                           password="******",
                                           port=port,
                                           debug=CLIENT_DEBUG)
        session.close()
        # NetconfSSHSession.flush()

        logger.debug("Closing")
        ns.close()
        logger.debug("Joining")
        ns.join()
    logger.debug("Test Complete")
Beispiel #3
0
def test_get_config_after_multiple_traps(server_debug, logger):

    session = client.NetconfSSHSession(SUT_IP,
                                       username=USER,
                                       password=PASSWORD,
                                       port=830,
                                       debug=server_debug)
    assert session

    errorIndication, errorStatus, errorIndex, varBinds = next(
        sendNotification(
            SnmpEngine(), CommunityData('public', mpModel=0),
            UdpTransportTarget((SUT_IP, 162)), ContextData(), 'trap',
            NotificationType(
                ObjectIdentity('1.3.6.1.6.3.1.1.5.2')).addVarBinds(
                    ('1.3.6.1.6.3.1.1.4.3.0', '1.3.6.1.4.1.20408.4.1.1.2'),
                    ('1.3.6.1.2.1.1.1.0', OctetString('my system')))))

    time.sleep(0.2)

    if errorIndication:
        logger.critical(errorIndication)
        assert 0, "Error sending SNMP trap"

    errorIndication, errorStatus, errorIndex, varBinds = next(
        sendNotification(
            SnmpEngine(), CommunityData('public', mpModel=0),
            UdpTransportTarget((SUT_IP, 162)), ContextData(), 'trap',
            NotificationType(
                ObjectIdentity('1.3.6.1.6.3.1.1.5.2')).addVarBinds(
                    ('1.3.6.1.6.3.1.1.4.3.0', '1.3.6.1.4.1.20408.4.1.1.2'),
                    ('1.3.6.1.2.1.1.1.0', OctetString('my system')))))

    if errorIndication:
        logger.critical(errorIndication)
        assert 0, "Error sending SNMP trap"

    time.sleep(0.2)

    query = """
    <nc:get-config xmlns:nc="urn:ietf:params:xml:ns:netconf:base:1.0" >
        <nc:source>
            <nc:running/>
        </nc:source>
        <nc:filter nc:type="subtree">
            <vnfi xmlns="urn:samsung:vnf-alarm-interface" xmlns:vaintf="urn:samsung:vnf-alarm-interface"/>
        </nc:filter>
    </nc:get-config>"""

    (_, _, answer) = session.send_rpc(query)

    logger.info("Answer received: " + str(answer))

    m = re.search("<rpc-reply.*<data.*<vnfi.*(<vnf-alarm.*){2}</rpc-reply",
                  answer,
                  flags=re.MULTILINE | re.DOTALL)

    assert m is not None, "Rpc reply does not seem to be ok"

    session.close()
Beispiel #4
0
def test_get_config(server_debug, logger):

    session = client.NetconfSSHSession(SUT_IP,
                                       username=USER,
                                       password=PASSWORD,
                                       port=830,
                                       debug=server_debug)
    assert session

    query = """
    <nc:get-config xmlns:nc="urn:ietf:params:xml:ns:netconf:base:1.0" >
        <nc:source>
           <nc:running/>
        </nc:source>
        <nc:filter nc:type="subtree">
            <vnfi xmlns="urn:samsung:vnf-alarm-interface" xmlns:vaintf="urn:samsung:vnf-alarm-interface"/>
        </nc:filter>
    </nc:get-config>"""

    (_, _, answer) = session.send_rpc(query)

    logger.info("Answer received: " + str(answer))

    m = re.search("<rpc-reply.*<data.*<vnfi.*</rpc-reply",
                  answer,
                  flags=re.MULTILINE | re.DOTALL)

    assert m is not None, "Rpc reply does not seem to be ok"

    session.close()
def test_multi_session():
    sessions = []
    for unused in range(0, 10):
        sessions.append(
            client.NetconfSSHSession("127.0.0.1",
                                     password="******",
                                     port=nc_server.port))
Beispiel #6
0
def test_subtree_explicit_ns_query_elm():
    select = etree.fromstring("""
        <foo:interfaces xmlns:foo="urn:test:mock">
        <foo:interface>
        <foo:name>Ethernet0/0</foo:name>
        <foo:state/>
        </foo:interface>
        </foo:interfaces>
        """)

    logger.info("Connecting to 127.0.0.1 port %d", NC_PORT)
    session = client.NetconfSSHSession("127.0.0.1",
                                       password="******",
                                       port=NC_PORT,
                                       debug=NC_DEBUG)

    cmptree = etree.fromstring("""
        <data xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
            <interfaces xmlns="urn:test:mock">
                <interface>
                    <name>Ethernet0/0</name>
                    <state>down</state>
                </interface>
            </interfaces>
        </data>""")

    results = session.get(select)
    assert (xml_eq(results, cmptree))
Beispiel #7
0
def test_create_subscription(server_debug, logger):

    session = client.NetconfSSHSession(SUT_IP,
                                       username=USER,
                                       password=PASSWORD,
                                       port=830,
                                       debug=server_debug)
    assert session

    query = """
    <ncn:create-subscription xmlns:ncn="urn:ietf:params:xml:ns:netconf:notification:1.0">
        <ncn:filter ncn:type="subtree">
            <vnf-alarm xmlns="urn:samsung:vnf-alarm-interface" xmlns:vaintf="urn:samsung:vnf-alarm-interface"/>      
            <vnf-alarm-rebuild-request xmlns="urn:samsung:vnf-alarm-interface" xmlns:vaintf="urn:samsung:vnf-alarm-interface"/>
            <default-parameter-loss-notification xmlns="urn:samsung:vnf-deploy-interface" 
            xmlns:vdintf="urn:samsung:vnf-deploy-interface"/>    
        </ncn:filter>
    </ncn:create-subscription>"""

    (_, _, answer) = session.send_rpc(query)

    logger.info("Answer received: " + str(answer))

    m = re.search("<rpc-reply.*ok.*</rpc-reply",
                  answer,
                  flags=re.MULTILINE | re.DOTALL)

    assert m is not None, "Rpc reply does not seem to be ok"

    session.close()
def test_server_close():
    server_ctl = server.SSHUserPassController(username=getpass.getuser(),
                                              password="******")
    for i in range(0, 10):
        logger.debug("Starting %d iteration", i)
        ns = server.NetconfSSHServer(server_ctl=server_ctl,
                                     server_methods=NetconfMethods(),
                                     port=None,
                                     host_key="tests/host_key",
                                     debug=SERVER_DEBUG)
        port = ns.port

        logger.info("Connect to server on port %d", port)
        session = client.NetconfSSHSession("127.0.0.1",
                                           password="******",
                                           port=port,
                                           debug=CLIENT_DEBUG)
        session.close()
        # NetconfSSHSession.flush()

        logger.debug("Closing")
        ns.close()
        logger.debug("Joining")
        ns.join()
    logger.debug("Test Complete")
Beispiel #9
0
def test_create_subscription_and_wait_for_notif(server_debug, logger, caplog):

    session = client.NetconfSSHSession(SUT_IP,
                                       username=USER,
                                       password=PASSWORD,
                                       port=830,
                                       debug=server_debug)
    assert session

    query = """
    <ncn:create-subscription xmlns:ncn="urn:ietf:params:xml:ns:netconf:notification:1.0">
        <ncn:filter ncn:type="subtree">
          <vnf-alarm xmlns="urn:samsung:vnf-alarm-interface" xmlns:vaintf="urn:samsung:vnf-alarm-interface"/>      
          <vnf-alarm-rebuild-request xmlns="urn:samsung:vnf-alarm-interface" xmlns:vaintf="urn:samsung:vnf-alarm-interface"/>
          <default-parameter-loss-notification xmlns="urn:samsung:vnf-deploy-interface"
          xmlns:vdintf="urn:samsung:vnf-deploy-interface"/>    
        </ncn:filter>
    </ncn:create-subscription>"""

    (_, _, answer) = session.send_rpc(query)

    logger.info("Answer received: " + str(answer))

    m = re.search("<rpc-reply.*ok.*</rpc-reply",
                  answer,
                  flags=re.MULTILINE | re.DOTALL)

    assert m is not None, "Rpc reply does not seem to be ok"

    time.sleep(0.2)

    # You can also use:
    # snmptrap -v1 -c public 127.0.0.1 1.3.6.1.4.1.20408.4.1.1.2 127.0.0.1 1 1 123 1.3.6.1.2.1.1.1.0 s test

    errorIndication, errorStatus, errorIndex, varBinds = next(
        sendNotification(
            SnmpEngine(), CommunityData('public', mpModel=0),
            UdpTransportTarget((SUT_IP, 162)), ContextData(), 'trap',
            NotificationType(
                ObjectIdentity('1.3.6.1.6.3.1.1.5.2')).addVarBinds(
                    ('1.3.6.1.6.3.1.1.4.3.0', '1.3.6.1.4.1.20408.4.1.1.2'),
                    ('1.3.6.1.2.1.1.1.0', OctetString('my system')))))

    if errorIndication:
        logger.critical(errorIndication)
        assert 0, "Error sending SNMP trap"

    time.sleep(0.2)

    out = caplog.text

    m = re.search(
        "<notification.*alarm-type.*alarm-info.*alarm-code.*</notification",
        out,
        flags=re.MULTILINE | re.DOTALL)

    assert m is not None, "Notification has not been received"

    session.close()
Beispiel #10
0
def test_get_config_with_filter():
    session = client.NetconfSSHSession("127.0.0.1", port=ncserver.port)
    assert session

    query = "<get-config><source><running/></source><filter><foobar/></filter></get-config>"
    rval = session.send_rpc(query)
    assert rval
    session.close()
Beispiel #11
0
def test_get():
    session = client.NetconfSSHSession("127.0.0.1", port=ncserver.port)
    assert session

    query = "<get><filter><status/></filter></get>"
    rval = session.send_rpc(query)
    assert rval
    # logger.debug("Get: {}", rval)
    session.close()
Beispiel #12
0
def test_get_config():
    session = client.NetconfSSHSession("127.0.0.1", port=ncserver.port)
    assert session

    query = "<get-config><source><running/></source></get-config>"
    rval = session.send_rpc(query)
    assert rval
    # logger.debug("Get: {}", rval)
    session.close()
Beispiel #13
0
def test_bad_query():
    session = client.NetconfSSHSession("127.0.0.1",
                                       password="******",
                                       port=NC_PORT,
                                       debug=NC_DEBUG)
    try:
        _, _, output = session.send_rpc("<get><unknown/></get>")
        logger.warning("Got unexpected output: %s", str(output))
    except NetconfError:
        pass
Beispiel #14
0
def test_get_config_with_filter():
    session = client.NetconfSSHSession("127.0.0.1",
                                       password="******",
                                       port=nc_server.port)
    assert session

    query = "<get-config xmlns='urn:ietf:params:xml:ns:netconf:base:1.0'><source><running/></source><filter><foobar/></filter></get-config>"
    rval = session.send_rpc(query)
    assert rval
    session.close()
Beispiel #15
0
def test_bad_query():
    session = client.NetconfSSHSession("127.0.0.1",
                                       username=getpass.getuser(),
                                       password="******",
                                       port=nc_server.port,
                                       debug=NC_DEBUG)
    try:
        unused, unused, output = session.send_rpc("<get><unknown/></get>")
        logger.warning("Got unexpected output: %s", str(output))
    except RPCError:
        pass
Beispiel #16
0
def test_get_config():
    session = client.NetconfSSHSession("127.0.0.1",
                                       password="******",
                                       port=nc_server.port)
    assert session

    query = "<get-config xmlns='urn:ietf:params:xml:ns:netconf:base:1.0'><source><running/></source></get-config>"
    rval = session.send_rpc(query)
    assert rval
    # logger.debug("Get: {}", rval)
    session.close()
Beispiel #17
0
def test_get():
    session = client.NetconfSSHSession("127.0.0.1",
                                       password="******",
                                       port=nc_server.port)
    assert session

    query = "<get xmlns='urn:ietf:params:xml:ns:netconf:base:1.0'><filter><status/></filter></get>"
    rval = session.send_rpc(query)
    assert rval
    # logger.debug("Get: {}", rval)
    session.close()
Beispiel #18
0
def test_not_supported():
    session = client.NetconfSSHSession("127.0.0.1", port=ncserver.port)
    assert session

    query = "<foobar/>"
    try:
        rval = session.send_rpc(query)
    except RPCError as error:
        assert error.get_error_tag() == "operation-not-supported"
    else:
        logger.error("Unexpected success: {}", rval)
        assert False
Beispiel #19
0
def test_malformed():
    session = client.NetconfSSHSession("127.0.0.1", port=ncserver.port)
    assert session

    query = "<get><foobar/></get><get/>"
    try:
        rval = session.send_rpc(query)
    except RPCError as error:
        assert error.get_error_tag() == "malformed-message"
    else:
        logger.error("Unexpected success: %s", str(rval))
        assert False
Beispiel #20
0
def test_xpath_query():
    query = """
    <get>
    <filter type="xpath" select="/devices/global-settings"/>
    </get>
    """
    logger.info("Connecting to 127.0.0.1 port %d", NC_PORT)
    session = client.NetconfSSHSession("127.0.0.1",
                                       password="******",
                                       port=NC_PORT,
                                       debug=NC_DEBUG)
    session.send_rpc(query)
Beispiel #21
0
def test_bad_password():
    try:
        cache = SSHNoConnectionCache("SSH uncached connections")
        session = client.NetconfSSHSession("127.0.0.1",
                                           password="******",
                                           port=nc_server.port,
                                           cache=cache)
    except ssh.AuthenticationException:
        pass
    else:
        logger.error("Unexpected success: %s", str(session))
        assert False
Beispiel #22
0
def test_get_config():
    session = client.NetconfSSHSession("127.0.0.1",
                                       password="******",
                                       port=nc_server.port)
    assert session

    query = "<get-config><source><running/></source></get-config>"
    rval = session.send_rpc(query)
    print "GET CONFIG REPLY ", rval

    assert rval
    # logger.debug("Get: {}", rval)
    session.close()
Beispiel #23
0
def test_get_config_missing_source():
    session = client.NetconfSSHSession("127.0.0.1", port=ncserver.port)
    assert session

    query = "<get-config></get-config>"
    try:
        rval = session.send_rpc(query)
    except RPCError as error:
        assert error.get_error_tag() == "missing-element"
    else:
        logger.error("Unexpected success: %s", str(rval))
        assert False
    session.close()
Beispiel #24
0
def test_get_config_with_non_filter():
    session = client.NetconfSSHSession("127.0.0.1", port=ncserver.port)
    assert session

    query = """<get-config><source><running/></source><foobar/></get-config>"""
    try:
        rval = session.send_rpc(query)
    except RPCError as error:
        assert error.get_error_tag() == "unknown-element"
    else:
        logger.error("Unexpected success: %s", str(rval))
        assert False
    session.close()
Beispiel #25
0
def test_namespaced_rpc():
    """TEST: Checked that namespaced RPCs work."""
    session = client.NetconfSSHSession("127.0.0.1",
                                       password="******",
                                       port=nc_server.port)
    assert session

    query = '<namespaced xmlns="some:namespace:1.0"></namespaced>'
    rval = session.send_rpc(query)
    rval = session.send_rpc(query)
    assert rval
    # logger.debug("Get: {}", rval)
    session.close()
Beispiel #26
0
def test_malformed():
    session = client.NetconfSSHSession("127.0.0.1",
                                       password="******",
                                       port=nc_server.port)
    assert session

    query = "<get xmlns='urn:ietf:params:xml:ns:netconf:base:1.0'><foobar/></get><get/>"
    try:
        rval = session.send_rpc(query)
    except RPCError as error:
        assert error.get_error_tag() == "malformed-message"
    else:
        logger.error("Unexpected success: %s", str(rval))
        assert False
Beispiel #27
0
def test_query ():
    query = """
    <get>
    <filter>
    <devices xmlns="http://tail-f.com/ns/ncs">
    <global-settings/>
    </devices>
    </filter>
    </get>
    """
    logger.info("Connecting to 127.0.0.1 port %d", nc_server.port)
    session = client.NetconfSSHSession("127.0.0.1",
                                       password="******",
                                       port=nc_server.port,
                                       debug=NC_DEBUG)
    session.send_rpc(query)
Beispiel #28
0
def test_malformed_2():
    session = client.NetconfSSHSession("127.0.0.1",
                                       port=ncserver.port,
                                       debug=True)
    assert session

    query = "</foobar>"
    try:
        rval = session.send_rpc(query)
    except RPCError as error:
        assert error.get_error_tag() == "malformed-message"
        session.close()
    except SessionError as error:
        # If the session closes that's OK too.
        pass
    else:
        logger.error("Unexpected success: %s", str(rval))
        assert False
Beispiel #29
0
def main(*margs):
    parser = argparse.ArgumentParser("Netconf Client Utility")
    parser.add_argument("--debug", action="store_true", help="Enable debug logging")
    parser.add_argument('--host', default="localhost", help='Netconf server hostname')
    parser.add_argument('--port', default="830", help='Netconf server port')
    parser.add_argument(
        '--hello', action="store_true", help="Do hello and return capabilities of server.")
    parser.add_argument("-i", "--infile", help="File to read from")
    parser.add_argument('-p', '--password', default=None, help='Netconf password')
    parser.add_argument(
        '--passenv', default=None, help='Environment variable holding Cassandra password')
    parser.add_argument("-q", "--quiet", action="store_true", help="Quiet operation")
    parser.add_argument('-u', '--username', default="admin", help='Netconf username')
    parser.add_argument("-v", "--verbose", action="store_true", help="Verbose logging")
    args = parser.parse_args(*margs)

    if args.passenv and args.password:
        print("Only one of --password and --passenv allowed", file=sys.stderr)
        sys.exit(1)
    if args.passenv:
        args.password = os.environ[args.passenv]

    if args.debug:
        logging.basicConfig(level=logging.DEBUG)
    elif args.verbose:
        logging.basicConfig(level=logging.INFO)
    elif args.quiet:
        logging.basicConfig(level=logging.ERROR)
    else:
        logging.basicConfig(level=logging.WARNING)

    session = client.NetconfSSHSession(
        args.host, args.port, args.username, args.password, debug=args.debug)
    if args.hello:
        print("\n".join(session.capabilities))
        sys.exit(0)

    if args.infile:
        xml = open(args.infile).read()
    else:
        xml = sys.stdin.read()
    result = session.send_rpc(xml)
    sys.stdout.write(result[2])
    session.close()
Beispiel #30
0
def test_get(server_debug, logger):

    session = client.NetconfSSHSession(SUT_IP,
                                       username=USER,
                                       password=PASSWORD,
                                       port=830,
                                       debug=server_debug)
    assert session

    query = "<get><filter><status/></filter></get>"
    logger.info("Capabilities received: " + str(session.capabilities))
    (_, _, answer) = session.send_rpc(query)

    m = re.search("<rpc-reply.*ok.*</rpc-reply",
                  answer,
                  flags=re.MULTILINE | re.DOTALL)

    assert m is not None, "Rpc reply does not seem to be ok"

    session.close()