コード例 #1
0
def gnmi_get(task: Task, path) -> Result:
    with gNMIclient(target=(task.host.hostname, task.host.port), username=task.host.username,
                    password=task.host.password, insecure=True) as gc:

        r = gc.get(path=path)

    return Result(host=task.host, result=r)
コード例 #2
0
def gnmi_capabilites(task: Task) -> Result:
    with gNMIclient(target=(task.host.hostname, task.host.port), username=task.host.username,
                    password=task.host.password, insecure=True) as gc:

        r = gc.capabilities()

    return Result(host=task.host, result=r)
コード例 #3
0
def test_set_update(msg1: tuple = test_set_update_tuple):
    load_dotenv()
    username_str = os.getenv("USER")
    password_str = os.getenv("PASS")
    hostname_str = os.getenv("HOST")
    port_str = os.getenv("PORT")
    path_cert_str = os.getenv("CERT")

    with gNMIclient(target=(hostname_str, port_str),
                    username=username_str,
                    password=password_str,
                    path_cert=path_cert_str) as gc:
        gc.capabilities()

        # Pre-change state
        result = gc.get(path=[msg1[0]])
        assert not "update" in result["notification"][0]

        # Set update
        result = gc.set(update=[msg1])
        assert "response" in result
        assert isinstance(result["response"], list)
        assert len(result["response"]) == 1
        assert "op" in result["response"][0]
        assert result["response"][0]["op"] == "UPDATE"
        assert "path" in result["response"][0]
        assert result["response"][0]["path"] in msg1[0]

        # Post-change state
        result = gc.get(path=[msg1[0]])
        assert "update" in result["notification"][0]
        assert isinstance(result["notification"][0]["update"], list)
        assert len(result["notification"][0]["update"]) == 1
コード例 #4
0
ファイル: test_functionality.py プロジェクト: jamie01/pygnmi
def test_set_delete(msg1: tuple = test_set_update_tuple,
                    path2: str = test_delete_second_str):
    load_dotenv()
    username_str = os.getenv("PYGNMI_USER")
    password_str = os.getenv("PYGNMI_PASS")
    hostname_str = os.getenv("PYGNMI_HOST")
    port_str = os.getenv("PYGNMI_PORT")
    path_cert_str = os.getenv("PYGNMI_CERT")

    with gNMIclient(target=(hostname_str, port_str),
                    username=username_str,
                    password=password_str,
                    path_cert=path_cert_str) as gc:
        gc.capabilities()

        # Pre-change state
        result = gc.get(path=[msg1[0]])
        assert "update" in result["notification"][0]
        assert isinstance(result["notification"][0]["update"], list)
        assert len(result["notification"][0]["update"]) == 1

        # Set delete
        result = gc.set(delete=[path2, msg1[0]])
        assert "response" in result
        assert isinstance(result["response"], list)
        assert len(result["response"]) == 2
        assert "op" in result["response"][0]
        assert result["response"][0]["op"] == "DELETE"
        assert "path" in result["response"][0]
        assert result["response"][0]["path"] in path2
        assert "op" in result["response"][1]
        assert result["response"][1]["op"] == "DELETE"
        assert "path" in result["response"][0]
        assert result["response"][1]["path"] in msg1[0]
コード例 #5
0
ファイル: test_functionality.py プロジェクト: jamie01/pygnmi
def test_get_multiple_paths():
    load_dotenv()
    username_str = os.getenv("PYGNMI_USER")
    password_str = os.getenv("PYGNMI_PASS")
    hostname_str = os.getenv("PYGNMI_HOST")
    port_str = os.getenv("PYGNMI_PORT")
    path_cert_str = os.getenv("PYGNMI_CERT")

    with gNMIclient(target=(hostname_str, port_str),
                    username=username_str,
                    password=password_str,
                    path_cert=path_cert_str) as gc:
        gc.capabilities()

        # Two paths
        result = gc.get(path=[
            "/openconfig-interfaces:interfaces",
            "/openconfig-network-instance:network-instances"
        ])
        assert "notification" in result
        assert isinstance(result["notification"], list)
        assert len(result["notification"]) == 2
        assert "update" in result["notification"][0]
        assert isinstance(result["notification"][0]["update"], list)
        assert len(result["notification"][0]["update"]) == 1
        assert "update" in result["notification"][1]
        assert isinstance(result["notification"][1]["update"], list)
        assert len(result["notification"][1]["update"]) == 1
コード例 #6
0
ファイル: test_functionality.py プロジェクト: jamie01/pygnmi
def test_set_replace(msg1: tuple = test_set_update_tuple,
                     msg2: tuple = test_set_replace_tuple):
    load_dotenv()
    username_str = os.getenv("PYGNMI_USER")
    password_str = os.getenv("PYGNMI_PASS")
    hostname_str = os.getenv("PYGNMI_HOST")
    port_str = os.getenv("PYGNMI_PORT")
    path_cert_str = os.getenv("PYGNMI_CERT")

    with gNMIclient(target=(hostname_str, port_str),
                    username=username_str,
                    password=password_str,
                    path_cert=path_cert_str) as gc:
        gc.capabilities()

        # Pre-change state
        result = gc.get(path=[msg1[0]])
        assert "path" in result["notification"][0]["update"][0]
        assert result["notification"][0]["update"][0]["path"] in msg1[0]
        assert "val" in result["notification"][0]["update"][0]
        assert "openconfig-interfaces:config" in result["notification"][0][
            "update"][0]["val"]
        assert "description" in result["notification"][0]["update"][0]["val"][
            "openconfig-interfaces:config"]
        assert result["notification"][0]["update"][0]["val"][
            "openconfig-interfaces:config"]["description"] == msg1[1][
                "config"]["description"]

        # Set replace
        result = gc.set(replace=[msg2])
        assert "response" in result
        assert isinstance(result["response"], list)
        assert len(result["response"]) == 1
        assert "op" in result["response"][0]
        assert result["response"][0]["op"] == "REPLACE"
        assert "path" in result["response"][0]
        assert result["response"][0]["path"] in msg2[0]

        # Post-change state
        result = gc.get(path=[msg2[0]])
        assert "path" in result["notification"][0]["update"][0]
        assert result["notification"][0]["update"][0]["path"] in msg2[0]
        assert "val" in result["notification"][0]["update"][0]
        assert "openconfig-interfaces:description" in result["notification"][
            0]["update"][0]["val"]
        assert result["notification"][0]["update"][0]["val"][
            "openconfig-interfaces:description"] == msg2[1]["description"]
コード例 #7
0
ファイル: test_functionality.py プロジェクト: jamie01/pygnmi
def test_capabilities():
    load_dotenv()
    username_str = os.getenv("PYGNMI_USER")
    password_str = os.getenv("PYGNMI_PASS")
    hostname_str = os.getenv("PYGNMI_HOST")
    port_str = os.getenv("PYGNMI_PORT")
    path_cert_str = os.getenv("PYGNMI_CERT")

    with gNMIclient(target=(hostname_str, port_str),
                    username=username_str,
                    password=password_str,
                    path_cert=path_cert_str) as gc:
        result = gc.capabilities()

    assert "supported_models" in result
    assert "supported_encodings" in result
    assert "gnmi_version" in result
コード例 #8
0
def test_telemetry_once(subscribe1: dict = test_telemetry_dict_once):
    load_dotenv()
    username_str = os.getenv("PYGNMI_USER")
    password_str = os.getenv("PYGNMI_PASS")
    hostname_str = os.getenv("PYGNMI_HOST")
    port_str = os.getenv("PYGNMI_PORT")
    path_cert_str = os.getenv("PYGNMI_CERT")

    with gNMIclient(target=(hostname_str, port_str), username=username_str, 
                    password=password_str, path_cert=path_cert_str) as gc:
        gc.capabilities()

        telemetry_iterator = gc.subscribe2(subscribe=subscribe1)
        telemetry_entry_item = telemetry_iterator.__next__()

        assert "update" in telemetry_entry_item or "sync_response" in telemetry_entry_item

        telemetry_iterator.close()
コード例 #9
0
def test_ipv4_address_certificate_download():
    load_dotenv()
    username_str = os.getenv("PYGNMI_USER")
    password_str = os.getenv("PYGNMI_PASS")
    hostname_str = os.getenv("PYGNMI_HOST_2")
    port_str = os.getenv("PYGNMI_PORT")
    path_cert_str = os.getenv("PYGNMI_CERT")

    gc = gNMIclient(target=(hostname_str, port_str),
                    username=username_str,
                    password=password_str)
    gc.connect()

    result = gc.capabilities()

    gc.close()

    assert "supported_models" in result
    assert "supported_encodings" in result
    assert "gnmi_version" in result
コード例 #10
0
def test_capabilities_connect_method():
    load_dotenv()
    username_str = os.getenv("USER")
    password_str = os.getenv("PASS")
    hostname_str = os.getenv("HOST")
    port_str = os.getenv("PORT")
    path_cert_str = os.getenv("CERT")

    gc = gNMIclient(target=(hostname_str, port_str),
                    username=username_str,
                    password=password_str,
                    path_cert=path_cert_str)
    gc.connect()

    result = gc.capabilities()

    gc.close()

    assert "supported_models" in result
    assert "supported_encodings" in result
    assert "gnmi_version" in result
コード例 #11
0
def test_get_connect_method():
    load_dotenv()
    username_str = os.getenv("USER")
    password_str = os.getenv("PASS")
    hostname_str = os.getenv("HOST")
    port_str = os.getenv("PORT")
    path_cert_str = os.getenv("CERT")

    gc = gNMIclient(target=(hostname_str, port_str),
                    username=username_str,
                    password=password_str,
                    path_cert=path_cert_str)
    gc.connect()

    gc.capabilities()
    result = gc.get(path=["/"])

    gc.close()

    assert "notification" in result
    assert isinstance(result["notification"], list)
コード例 #12
0
    def __init__(self, stepDict, method="gnmi", port=50051):

        self.logger = logging.getLogger()
        logging.basicConfig(format='%(levelname)s:%(message)s',
                            level=logging.DEBUG)

        self.hostname = stepDict.get("device")
        self.port = stepDict.get("port", port)
        self.initConnectTs = datetime.datetime.now()
        self.username = stepDict.get("username")
        self.timeout = stepDict.get("timeout", 10)
        self.insecure = stepDict.get("insecure", True)
        self.override = stepDict.get("override", False)
        self.password = stepDict.get("password")
        self.connected = False
        self.connectTries = 1
        try:
            host = (self.hostname, self.port)
            self.logger.info("connect host %s", host)
            self.gc = gNMIclient(target=host,
                                 debug=True,
                                 username=self.username,
                                 password=self.password,
                                 insecure=self.insecure)
            self.gc.__enter__()
        except Exception as exc:
            self.logger.error("error: %s\n %s", exc, traceback.format_exc())
            self.logger.error('Error on line %s', sys.exc_info()[-1].tb_lineno)
            self.logger.warning("connect to %s port %s failed: %s",
                                self.hostname, self.port, exc)
            raise Exception("cannot connect")
        else:
            self.logger.info("connect succeeded to {} port {}".format(
                self.hostname, self.port))
            self.connected = True
            self.ts = []  #telemetry stream
            self.nb_ts = None
コード例 #13
0
ファイル: subscribe_stream.py プロジェクト: jamie01/pygnmi
    if host_entry["nos"] == "nokia-sros":
        subscribe = {
            'subscription': [{
                'path':
                'openconfig-interfaces:interfaces/interface[name=1/1/c1/1]',
                'mode': 'sample',
                'sample_interval': 10000000000
            }, {
                'path':
                'openconfig-network-instance:network-instances/network-instance[name=Base]/interfaces/interface[id=1/1/c1/1.0]',
                'mode': 'sample',
                'sample_interval': 10000000000
            }],
            'use_aliases':
            False,
            'mode':
            'stream',
            'encoding':
            'json'
        }

        with gNMIclient(target=(host_entry["ip_address"], host_entry["port"]),
                        username=host_entry["username"],
                        password=host_entry["password"],
                        insecure=True) as gc:

            telemetry_stream = gc.subscribe_stream(subscribe=subscribe)

            for telemetry_entry in telemetry_stream:
                print(telemetry_entry)
コード例 #14
0
ファイル: set_tls.py プロジェクト: slieberth/pygnmi
#!/usr/bin/env python

# Modules
from pygnmi.client import gNMIclient
import json

host = ('10.127.60.177', '57400')
set_config = [("openconfig-system:system", {
    "config": {
        "hostname": "BH1_P2A5"
    }
})]
del_config = [
    "openconfig-interfaces:interfaces/interface[name=\"Optics0/0/0/0\"]"
]

if __name__ == '__main__':

    with gNMIclient(
            target=host,
            username='******',
            password='******',
            path_cert='/ws/avpathak-bgl/BossHogg/openconfig/ems_BH_P2A4.pem',
            override='ems.cisco.com',
            debug=True) as gc:
        # result = gc.set(update=set_config)
        result = gc.set(delete=del_config)
        print(result)
コード例 #15
0
from pygnmi.client import gNMIclient, telemetryParser

subscribe = {
            'subscription': [
                {
                    'path': 'interfaces/interface[name=Ethernet1]/state/counters',
                    'mode': 'sample',
                    'sample_interval': 10000000000
                },
                {
                    'path': 'network-instances/network-instance/protocols/protocol/bgp/neighbors/neighbor/state',
                    'mode': 'sample',
                    'sample_interval': 10000000000
                }
            ],
            'mode': 'stream',
            'encoding': 'json'
        }

host = ('10.73.1.105', '6030')

with gNMIclient(target=host, username='******', password='******', insecure=True) as gc:
    telemetry_stream = gc.subscribe(subscribe=subscribe)
    for telemetry_entry in telemetry_stream:
                print(telemetryParser(telemetry_entry))


コード例 #16
0
def main():

    # Setting logger
    if not os.path.exists(path_log.split('/')[0]):
        os.mkdir(path_log.split('/')[0])

    logging.basicConfig(
        filename=path_log,
        level=logging.INFO,
        format='%(asctime)s.%(msecs)03d+01:00,%(levelname)s,%(message)s',
        datefmt='%Y-%m-%dT%H:%M:%S'
    )
    logging.info('Starting application...')

    # Collecting inputs
    args = parse_args(msg)

    # gNMI operation
    with gNMIclient(
        target=args.target, username=args.username, password=args.password,
        path_cert=args.path_cert, path_key=args.path_key, path_root=args.path_root,
        override=args.override, insecure=args.insecure, debug=args.print,
    ) as GC:

        result = None

        if args.operation == 'capabilities':
            print(f'Doing {args.operation} request to {args.target}...')
            result = GC.capabilities()

        elif args.operation == 'get':
            print(f'Doing {args.operation} request to {args.target}...')
            result = GC.get(args.gnmi_path, datatype=args.datastore, encoding='json')

        elif args.operation.startswith('set'):
            print(f'Doing {args.operation} request to {args.target}...')
            mode = args.operation.split("-")[1]
            kwargs = {}
            if mode == "delete":
                # For a delete request, give kwarg delete=[path]
                kwargs[mode] = args.gnmi_path
            else:
                # For update (or replace) request, give kwarg update=[(path, data)]
                with open(args.file, "r") as f:
                    data = f.read()
                jdata = json.loads(data)
                kwargs[mode] = [(args.gnmi_path[0], jdata)]
            result = GC.set(encoding="json_ietf", **kwargs)

        elif args.operation.startswith('subscribe'):
            mode = args.operation.split("-")[1]
            subscription_list = [
                {
                    'path': xpath,
                    'mode': 'sample',
                    'sample_interval': 10000000000,
                    'heartbeat_interval': 30000000000
                }
                for xpath in args.gnmi_path
            ]
            subscribe = {
                'subscription': subscription_list,
                'use_aliases': False,
                'mode': mode,
                'encoding': 'json'
            }

            result = GC.subscribe2(subscribe=subscribe)

            if mode == "stream":
                try:
                    for ent in result:
                        print(ent)
                except KeyboardInterrupt:
                    result.close()

            elif mode == "once":
                for ent in result:
                    print(ent)
                    if "sync_response" in ent:
                        break

            elif mode == "poll":
                while True:
                    try:
                        input("Press enter to poll, ctrl+c to quit")
                        ent = result.get_update(timeout=5)
                        print(ent)
                    except KeyboardInterrupt:
                        result.close()
                        break

        if result:
            print(result)
コード例 #17
0
from pygnmi.client import gNMIclient
from pprint import pprint as pp
import json

host = ('10.73.1.105', '6030')
username ='******'
password ='******'

with gNMIclient(target=host, username=username, password=password, insecure=True) as gc:
    result = gc.capabilities()
    pp(result)
    #print (json.dumps(result, sort_keys=True, indent=2))
コード例 #18
0
ファイル: test_functionality.py プロジェクト: jamie01/pygnmi
def test_get_signle_path_all_path_formats():
    load_dotenv()
    username_str = os.getenv("PYGNMI_USER")
    password_str = os.getenv("PYGNMI_PASS")
    hostname_str = os.getenv("PYGNMI_HOST")
    port_str = os.getenv("PYGNMI_PORT")
    path_cert_str = os.getenv("PYGNMI_CERT")

    with gNMIclient(target=(hostname_str, port_str),
                    username=username_str,
                    password=password_str,
                    path_cert=path_cert_str) as gc:
        gc.capabilities()

        # Default GNMI path
        result = gc.get(path=["/"])
        assert "notification" in result
        assert isinstance(result["notification"], list)
        assert len(result["notification"]) == 1
        assert "update" in result["notification"][0]
        assert isinstance(result["notification"][0]["update"], list)
        assert len(result["notification"][0]["update"]) > 0

        # "yang-model:top_element" GNMI path notation
        result = gc.get(path=["openconfig-interfaces:interfaces"])
        assert "notification" in result
        assert isinstance(result["notification"], list)
        assert len(result["notification"]) == 1
        assert "update" in result["notification"][0]
        assert isinstance(result["notification"][0]["update"], list)
        assert len(result["notification"][0]["update"]) == 1

        # "yang-model:top_element/next_element" GNMI path notation
        result = gc.get(path=["openconfig-interfaces:interfaces/interface"])
        assert "notification" in result
        assert isinstance(result["notification"], list)
        assert len(result["notification"]) == 1
        assert "update" in result["notification"][0]
        assert isinstance(result["notification"][0]["update"], list)
        assert len(result["notification"][0]["update"]) > 0

        # "/yang-model:top_element/next_element" GNMI path notation
        result = gc.get(path=["/openconfig-interfaces:interfaces/interface"])
        assert "notification" in result
        assert isinstance(result["notification"], list)
        assert len(result["notification"]) == 1
        assert "update" in result["notification"][0]
        assert isinstance(result["notification"][0]["update"], list)
        assert len(result["notification"][0]["update"]) > 0

        # "/yang-model:/top_element/next_element" GNMI path notation
        result = gc.get(path=["/openconfig-interfaces:/interfaces/interface"])
        assert "notification" in result
        assert isinstance(result["notification"], list)
        assert len(result["notification"]) == 1
        assert "update" in result["notification"][0]
        assert isinstance(result["notification"][0]["update"], list)
        assert len(result["notification"][0]["update"]) > 0

        # "top_element" GNMI path notation
        result = gc.get(path=["interfaces"])
        assert "notification" in result
        assert isinstance(result["notification"], list)
        assert len(result["notification"]) == 1
        assert "update" in result["notification"][0]
        assert isinstance(result["notification"][0]["update"], list)
        assert len(result["notification"][0]["update"]) == 1

        # "top_element/next_element" GNMI path notation
        result = gc.get(path=["interfaces/interface"])
        assert "notification" in result
        assert isinstance(result["notification"], list)
        assert len(result["notification"]) == 1
        assert "update" in result["notification"][0]
        assert isinstance(result["notification"][0]["update"], list)
        assert len(result["notification"][0]["update"]) > 0

        # "/top_element/next_element" GNMI path notation
        result = gc.get(path=["/interfaces/interface"])
        assert "notification" in result
        assert isinstance(result["notification"], list)
        assert len(result["notification"]) == 1
        assert "update" in result["notification"][0]
        assert isinstance(result["notification"][0]["update"], list)
        assert len(result["notification"][0]["update"]) > 0
コード例 #19
0
ファイル: pygnmicli.py プロジェクト: slieberth/pygnmi
    logging.basicConfig(
        filename=path_log,
        level=logging.INFO,
        format='%(asctime)s.%(msecs)03d+01:00,%(levelname)s,%(message)s',
        datefmt='%Y-%m-%dT%H:%M:%S')
    logging.info('Starting application...')

    # Collecting inputs
    del sys.argv[0]
    DD = NFData(sys.argv, msg)

    # gNMI operation
    with gNMIclient(DD.targets,
                    username=DD.username,
                    password=DD.password,
                    debug=DD.to_print,
                    insecure=DD.insecure,
                    path_cert="./cert.pem") as GC:
        result = None

        if DD.operation == 'capabilities':
            print(f'Doing {DD.operation} request to {DD.targets}...')
            result = GC.capabilities()

        elif DD.operation == 'get':
            print(f'Doing {DD.operation} request to {DD.targets}...')
            result = GC.get(DD.gnmi_path, datatype='all', encoding='json')

        elif DD.operation == 'set':
            print(f'Doing {DD.operation} request to {DD.targets}...')
            deletes = DD.gnmi_path if DD.gnmi_path else None
コード例 #20
0
ファイル: subscribe_poll.py プロジェクト: jamie01/pygnmi
        paths = ["graphnos-frib:frib", "graphnos-interfaces:interfaces"]

        subscribes = [{
            'subscription': [{
                'path': path
            }],
            'mode': 'poll',
            'encoding': 'json_ietf'
        } for path in paths]

        prompt_msg = "\n".join([f"{i} - {path}" for i, path in enumerate(paths)] + \
                               ["Type path # to poll, or STOP: "])

        with gNMIclient(target=(host_entry["ip_address"], host_entry["port"]),
                        path_root=host_entry["path_root"],
                        path_cert=host_entry["path_cert"],
                        path_key=host_entry["path_key"],
                        override=host_entry["ssl_name"]) as gc:

            polls = [gc.subscribe_poll(subscribe=s) for s in subscribes]

            while True:
                cmd = input(prompt_msg)

                if cmd.isnumeric():
                    pathid = int(cmd)
                    notification = polls[pathid].get_update(timeout=5)
                    print(notification)

                elif cmd == "STOP":
                    [poll.close() for poll in polls]
コード例 #21
0
    logging.basicConfig(
        filename=path_log,
        level=logging.INFO,
        format='%(asctime)s.%(msecs)03d+01:00,%(levelname)s,%(message)s',
        datefmt='%Y-%m-%dT%H:%M:%S')
    logging.info('Starting application...')

    # Collecting inputs
    del sys.argv[0]
    DD = NFData(sys.argv, msg)

    # gNMI operation
    #    try:
    with gNMIclient(DD.targets,
                    username=DD.username,
                    password=DD.password,
                    debug=DD.to_print,
                    insecure=DD.insecure,
                    path_cert=DD.certificate) as GC:
        result = None

        if DD.operation == 'capabilities':
            print(f'Doing {DD.operation} request to {DD.targets}...')
            result = GC.capabilities()

        elif DD.operation == 'get':
            print(f'Doing {DD.operation} request to {DD.targets}...')
            result = GC.get(DD.gnmi_path, datatype='all', encoding='json')

        elif DD.operation == 'set':
            print(f'Doing {DD.operation} request to {DD.targets}...')
            deletes = DD.gnmi_path if DD.gnmi_path else None
コード例 #22
0
#!/usr/bin env python

# Modules
from pygnmi.client import gNMIclient

# Variables
host = ('192.168.56.31', 50051)

# Body
if __name__ == '__main__':
    with gNMIclient(target=host,
                    username='******',
                    password='******',
                    insecure=False) as gc:
        response = gc.capabilities()

    print(response)