Ejemplo n.º 1
0
 def get_endpoints(uri):
     client = Client(uri, timeout=2)
     client.connect_and_get_server_endpoints()
     edps = client.connect_and_get_server_endpoints()
     for i, ep in enumerate(edps, start=1):
         logger.info('Endpoint %s:', i)
         for (n, v) in endpoint_to_strings(ep):
             logger.info('  %s: %s', n, v)
         logger.info('')
     return edps
Ejemplo n.º 2
0
 def get_endpoints(uri):
     client = Client(uri, timeout=2)
     client.connect_and_get_server_endpoints()
     edps = client.connect_and_get_server_endpoints()
     for i, ep in enumerate(edps, start=1):
         logger.info('Endpoint %s:', i)
         for (n, v) in endpoint_to_strings(ep):
             logger.info('  %s: %s', n, v)
         logger.info('')
     return edps
Ejemplo n.º 3
0
def get_endpoints(uri):
    client = Client(uri, timeout=2)
    endpoints = client.connect_and_get_server_endpoints()
    for i, endpoint in enumerate(endpoints, start=1):
        print('[INFO]', 'Endpoint %s:' % i)
        for record in endpoint_to_strings(endpoint):  # name, value
            print('  >>>   %s: %s' % record)
    return endpoints
Ejemplo n.º 4
0
 def get_endpoints(uri):
     # Create client object and associate url of the server
     client = Client(uri)
     # Connect, ask server for endpoints, and disconnect
     edps = client.connect_and_get_server_endpoints()
     for i, ep in enumerate(edps, start=1):
         logger.info('Endpoint %s:', i)
         for n, v in endpoint_to_strings(ep):
             logger.info('  %s: %s', n, v)
         logger.info('')
     return edps
    def get_endpoints(self):

        uri = self.ui.addressComboBox.currentText()
        client = Client(uri, timeout=2)
        try:
            edps = client.connect_and_get_server_endpoints()
            for i, ep in enumerate(edps, start=1):
                self.log_window.ui.logTextEdit.append('Endpoint %s:' % i)
                for (n, v) in endpoint_to_strings(ep):
                    self.log_window.ui.logTextEdit.append('  %s: %s' % (n, v))
                self.log_window.ui.logTextEdit.append('')
        except Exception as ex:
            self.log_window.ui.logTextEdit.append(str(ex))
            raise
        return edps
Ejemplo n.º 6
0
def uadiscover():
    parser = argparse.ArgumentParser(
        description=
        "Performs OPC UA discovery and prints information on servers and endpoints."
    )
    add_minimum_args(parser)
    parser.add_argument(
        "-n",
        "--network",
        action="store_true",
        help="Also send a FindServersOnNetwork request to server")
    #parser.add_argument("-s",
    #"--servers",
    #action="store_false",
    #help="send a FindServers request to server")
    #parser.add_argument("-e",
    #"--endpoints",
    #action="store_false",
    #help="send a GetEndpoints request to server")
    args = parse_args(parser)

    client = Client(args.url, timeout=args.timeout)

    if args.network:
        print("Performing discovery at {0}\n".format(args.url))
        for i, server in enumerate(
                client.connect_and_find_servers_on_network(), start=1):
            print('Server {0}:'.format(i))
            #for (n, v) in application_to_strings(server):
            #print('  {}: {}'.format(n, v))
            print('')

    print("Performing discovery at {0}\n".format(args.url))
    for i, server in enumerate(client.connect_and_find_servers(), start=1):
        print('Server {0}:'.format(i))
        for (n, v) in application_to_strings(server):
            print('  {0}: {1}'.format(n, v))
        print('')

    for i, ep in enumerate(client.connect_and_get_server_endpoints(), start=1):
        print('Endpoint {0}:'.format(i))
        for (n, v) in endpoint_to_strings(ep):
            print('  {0}: {1}'.format(n, v))
        print('')

    sys.exit(0)
Ejemplo n.º 7
0
def client_security(security, url, timeout):
    parts = security.split(',')
    if len(parts) < 4:
        raise Exception('Wrong format: `{}`, expected at least 4 comma-separated values'.format(security))
    policy_class = getattr(security_policies, 'SecurityPolicy' + parts[0])
    mode = getattr(ua.MessageSecurityMode, parts[1])
    cert = open(parts[2], 'rb').read()
    pk = open(parts[3], 'rb').read()
    server_cert = None
    if len(parts) == 5:
        server_cert = open(parts[4], 'rb').read()
    else:
        # we need server's certificate too. Let's get it from the list of endpoints
        client = Client(url, timeout=timeout)
        for ep in client.connect_and_get_server_endpoints():
            if ep.EndpointUrl.startswith(ua.OPC_TCP_SCHEME) and ep.SecurityMode == mode and ep.SecurityPolicyUri == policy_class.URI:
                server_cert = ep.ServerCertificate
    return policy_class(server_cert, cert, pk, mode)
Ejemplo n.º 8
0
def uadiscover():
    parser = argparse.ArgumentParser(
        description="Performs OPC UA discovery and prints information on servers and endpoints."
    )
    add_minimum_args(parser)
    parser.add_argument(
        "-n", "--network", action="store_true", help="Also send a FindServersOnNetwork request to server"
    )
    # parser.add_argument("-s",
    # "--servers",
    # action="store_false",
    # help="send a FindServers request to server")
    # parser.add_argument("-e",
    # "--endpoints",
    # action="store_false",
    # help="send a GetEndpoints request to server")
    args = parse_args(parser)

    client = Client(args.url, timeout=args.timeout)

    if args.network:
        print("Performing discovery at {}\n".format(args.url))
        for i, server in enumerate(client.connect_and_find_servers_on_network(), start=1):
            print("Server {}:".format(i))
            # for (n, v) in application_to_strings(server):
            # print('  {}: {}'.format(n, v))
            print("")

    print("Performing discovery at {}\n".format(args.url))
    for i, server in enumerate(client.connect_and_find_servers(), start=1):
        print("Server {}:".format(i))
        for (n, v) in application_to_strings(server):
            print("  {}: {}".format(n, v))
        print("")

    for i, ep in enumerate(client.connect_and_get_server_endpoints(), start=1):
        print("Endpoint {}:".format(i))
        for (n, v) in endpoint_to_strings(ep):
            print("  {}: {}".format(n, v))
        print("")

    sys.exit(0)
Ejemplo n.º 9
0
    def provision_discovery_instance(self, instance_id: str, service_id: str, plan_id: str,
                                     parameters: dict=None) -> ProvisionedServiceSpec:
        url = parameters.get("discovery_url")
        if not url:
            return ProvisionedServiceSpec(state="failed")

        client = Client(url)

        print("Performing discovery at {0}\n".format(url))
        try:
            endpoints = client.connect_and_get_server_endpoints()

            service_instance = OpcuaServiceInstance(instance_id, service_id, plan_id, parameters)
            service_instance.params["endpoints"] = endpoints

            service_instance_map = dict()
            service_instance_map[instance_id] = service_instance
            self.service_instance_map = service_instance_map
        except Exception as e:
            print("Error: {0}\n".format(e))
            return ProvisionedServiceSpec(state="failed")

        print("Discovery service instance {0} is provisioned successfully\n".format(instance_id))
        return ProvisionedServiceSpec()
Ejemplo n.º 10
0
 def test_find_endpoints(self):
     c = Client(URL)
     res = c.connect_and_get_server_endpoints()
     self.assertTrue(len(res) > 0)
Ejemplo n.º 11
0
 def test_find_endpoints(self):
     c = Client(URL)
     res = c.connect_and_get_server_endpoints()
     self.assertTrue(len(res) > 0)
Ejemplo n.º 12
0
def run():
    logger.debug("Modular Input mi_opcua command: %s" % sys.argv)
    if len(sys.argv) > 1:
        try:
            if sys.argv[1] == "--scheme":
                do_scheme()
            elif sys.argv[1] == "--validate-arguments":
                validate_arguments()
            elif sys.argv[1] == "--test":
                test()
            else:
                usage()
        except Exception as ex:
            logger.critical(ex)
    else:
        logger.debug("Modular Input mi_opcua Starts data collection.")

        configs = get_config()
        logger.debug("Configuration: %s" % configs)
        stanza = configs["name"]
        SP = configs.get("separator", ":")
        patterns = configs["measures"].split(SP)
        tout = configs["connection_timeout"].strip()
        spec = configs.get("metrics_spec", "n.a.").strip()
        timeout = 1 if len(tout) <= 0 else int(tout)

        conn = configs[
            "connection"]  ## "opc.tcp://ec2-54-190-162-94.us-west-2.compute.amazonaws.com:49320"

        if configs.has_key("username"):
            username = configs["username"].strip()
            if len(username) > 0:
                password = configs["password"].strip()
                conn = "%s?username=%s&password=%s" % (conn, username,
                                                       password)

        client = Client(conn, timeout=timeout)

        mi.init_stream(sys.stdout)
        try:
            if logger.isEnabledFor(logging.DEBUG):
                try:
                    servers = client.connect_and_find_servers()
                    logger.debug("Servers are found: ")
                    for s in servers:
                        print s
                        logger.debug("\tServer: %s" % s)
                except:
                    pass

                try:
                    nservers = client.connect_and_find_servers_on_network()
                    logger.debug("Network Servers are found: ")
                    for n in nservers:
                        logger.debug("\tNetwork Server: %s" % n)
                except:
                    pass

                endpoints = None
                try:
                    endpoints = client.connect_and_get_server_endpoints()
                    logger.debug("Server Endpoints are found: ")
                    for e in endpoints:
                        logger.debug("\tServer Endpoint: %s" % e.EndpointUrl)
                        logger.debug("\t\tServer Details: %s" % e)
                except:
                    pass

            try:
                logger.info("Start connecting OPC Server [%s]." % conn)
                client.connect()
                logger.info("OPC Server [%s] is connected." % conn)
            except Exception as ex:
                logger.error("Connecting to [%s] failed." % conn)
                if endpoints and len(endpoints) > 0:
                    for ep in endpoints:
                        try:
                            conn = ep.EndpointUrl
                            logger.info(
                                "Try connect to another OPC Server [%s]." %
                                conn)
                            client = Client(conn, timeout=timeout)
                            client.connect()
                            logger.info("OPC Server [%s] is connected." % conn)
                        except:
                            break
                else:
                    raise ex

            measures = []
            root = client.get_root_node()

            node.collect_measures(measures, patterns, root)

            md = {}
            try:
                jm = os.path.join(ua.data_dir(), spec)
                with open(jm, 'r') as mfp:
                    md = json.load(mfp)
                    mfp.close()
            except:
                pass

            for m in measures:
                collect_data(stanza, m[len(m) - 1], spec=md)

        except Exception as ex:
            logger.critical(ex)
        finally:
            mi.fini_stream(sys.stdout)
            logger.info("---- end of opc ua ----")
            client.disconnect()