示例#1
0
    def test_integration_with_listener_v6_records(self):

        type_ = "_test-srvc-type._tcp.local."
        name = "xxxyyy"
        registration_name = "%s.%s" % (name, type_)
        addr = "2606:2800:220:1:248:1893:25c8:1946"  # example.com

        zeroconf_registrar = Zeroconf(interfaces=['127.0.0.1'])
        desc = {'path': '/~paulsm/'}
        info = ServiceInfo(
            type_,
            registration_name,
            80,
            0,
            0,
            desc,
            "ash-2.local.",
            addresses=[socket.inet_pton(socket.AF_INET6, addr)],
        )
        zeroconf_registrar.register_service(info)
        _clear_cache(zeroconf_registrar)
        try:
            service_types = ZeroconfServiceTypes.find(interfaces=['127.0.0.1'],
                                                      timeout=0.5)
            assert type_ in service_types
            _clear_cache(zeroconf_registrar)
            service_types = ZeroconfServiceTypes.find(zc=zeroconf_registrar,
                                                      timeout=0.5)
            assert type_ in service_types

        finally:
            zeroconf_registrar.close()
示例#2
0
    def test_integration_with_listener_ipv6(self):

        type_ = "_test-srvc-type._tcp.local."
        name = "xxxyyy"
        registration_name = "%s.%s" % (name, type_)

        zeroconf_registrar = Zeroconf(ip_version=r.IPVersion.V6Only)
        desc = {'path': '/~paulsm/'}
        info = ServiceInfo(
            type_,
            registration_name,
            80,
            0,
            0,
            desc,
            "ash-2.local.",
            addresses=[socket.inet_aton("10.0.1.2")],
        )
        zeroconf_registrar.register_service(info)
        _clear_cache(zeroconf_registrar)
        try:
            service_types = ZeroconfServiceTypes.find(
                ip_version=r.IPVersion.V6Only, timeout=0.5)
            assert type_ in service_types
            _clear_cache(zeroconf_registrar)
            service_types = ZeroconfServiceTypes.find(zc=zeroconf_registrar,
                                                      timeout=0.5)
            assert type_ in service_types

        finally:
            zeroconf_registrar.close()
示例#3
0
    def test_integration_with_listener(self):

        type_ = "_test-srvc-type._tcp.local."
        name = "xxxyyy"
        registration_name = "%s.%s" % (name, type_)

        zeroconf_registrar = Zeroconf(interfaces=["127.0.0.1"])
        desc = {"path": "/~paulsm/"}
        info = ServiceInfo(
            type_,
            registration_name,
            socket.inet_aton("10.0.1.2"),
            80,
            0,
            0,
            desc,
            "ash-2.local.",
        )
        zeroconf_registrar.register_service(info)

        try:
            service_types = ZeroconfServiceTypes.find(interfaces=["127.0.0.1"],
                                                      timeout=0.5)
            assert type_ in service_types
            service_types = ZeroconfServiceTypes.find(zc=zeroconf_registrar,
                                                      timeout=0.5)
            assert type_ in service_types

        finally:
            zeroconf_registrar.close()
    def test_integration_with_subtype_and_listener(self):
        subtype_ = "_subtype._sub"
        type_ = "_type._tcp.local."
        name = "xxxyyy"
        # Note: discovery returns only DNS-SD type not subtype
        discovery_type = "%s.%s" % (subtype_, type_)
        registration_name = "%s.%s" % (name, type_)

        zeroconf_registrar = Zeroconf(interfaces=['127.0.0.1'])
        desc = {'path': '/~paulsm/'}
        info = ServiceInfo(
            discovery_type, registration_name,
            socket.inet_aton("10.0.1.2"), 80, 0, 0,
            desc, "ash-2.local.")
        zeroconf_registrar.register_service(info)

        try:
            service_types = ZeroconfServiceTypes.find(
                interfaces=['127.0.0.1'], timeout=0.5)
            assert discovery_type in service_types
            service_types = ZeroconfServiceTypes.find(
                zc=zeroconf_registrar, timeout=0.5)
            assert discovery_type in service_types

        finally:
            zeroconf_registrar.close()
示例#5
0
    def test_integration_with_subtype_and_listener(self):
        subtype_ = "_subtype._sub"
        type_ = "_type._tcp.local."
        name = "xxxyyy"
        # Note: discovery returns only DNS-SD type not subtype
        discovery_type = "%s.%s" % (subtype_, type_)
        registration_name = "%s.%s" % (name, type_)

        zeroconf_registrar = Zeroconf(interfaces=["127.0.0.1"])
        desc = {"path": "/~paulsm/"}
        info = ServiceInfo(
            discovery_type,
            registration_name,
            socket.inet_aton("10.0.1.2"),
            80,
            0,
            0,
            desc,
            "ash-2.local.",
        )
        zeroconf_registrar.register_service(info)

        try:
            service_types = ZeroconfServiceTypes.find(interfaces=["127.0.0.1"],
                                                      timeout=0.5)
            assert discovery_type in service_types
            service_types = ZeroconfServiceTypes.find(zc=zeroconf_registrar,
                                                      timeout=0.5)
            assert discovery_type in service_types

        finally:
            zeroconf_registrar.close()
示例#6
0
 def run(self):
     _ = ServiceBrowser(self.zeroconf,
                        "_http._tcp.local.",
                        handlers=[self.on_service_change])
     try:
         while True:
             ZeroconfServiceTypes.find()
             sleep(10)
     except (KeyboardInterrupt, InvalidServiceAddedException):
         pass
     finally:
         self.zeroconf.close()
示例#7
0
    def get_services(self, timeout: int = 5) -> List[str]:
        """
        Get the full list of services found on the network.

        :param timeout: Discovery timeout in seconds (default: 5).
        :return: List of the services as strings.
        """
        return list(ZeroconfServiceTypes.find(timeout=timeout))
示例#8
0
def get_service():
    # Open a file
    #fo = open("services.txt", "wb")
    #fo.write('\n'.join(ZeroconfServiceTypes.find()))
    str = ('\n'.join(ZeroconfServiceTypes.find()))
    module_name = MN.info()
    module_name = module_name.strip()
    module_name = module_name.split('.')[1]
    return (str, module_name)
示例#9
0
    def test_integration_with_listener(self):

        type_ = "_test-srvc-type._tcp.local."
        name = "xxxyyy"
        registration_name = "%s.%s" % (name, type_)

        zeroconf_registrar = Zeroconf(interfaces=['127.0.0.1'])
        desc = {'path': '/~paulsm/'}
        info = ServiceInfo(
            type_, registration_name, socket.inet_aton("10.0.1.2"), 80, 0, 0, desc, "ash-2.local."
        )
        zeroconf_registrar.register_service(info)

        try:
            service_types = ZeroconfServiceTypes.find(interfaces=['127.0.0.1'], timeout=0.5)
            assert type_ in service_types
            service_types = ZeroconfServiceTypes.find(zc=zeroconf_registrar, timeout=0.5)
            assert type_ in service_types

        finally:
            zeroconf_registrar.close()
def main():
    logging.basicConfig(level=logging.DEBUG)

    parser = argparse.ArgumentParser()
    parser.add_argument('--debug', action='store_true')
    parser.add_argument('--find',
                        action='store_true',
                        help='Browse all available services')
    version_group = parser.add_mutually_exclusive_group()
    version_group.add_argument('--v6', action='store_true')
    version_group.add_argument('--v6-only', action='store_true')
    args = parser.parse_args()

    if args.debug:
        logging.getLogger('zeroconf').setLevel(logging.DEBUG)
    if args.v6:
        ip_version = IPVersion.All
    elif args.v6_only:
        ip_version = IPVersion.V6Only
    else:
        ip_version = IPVersion.V4Only

    zeroconf = Zeroconf(ip_version=ip_version)

    services = ["_http._tcp.local.", "_hap._tcp.local."]
    if args.find:
        services = list(ZeroconfServiceTypes.find(zc=zeroconf))

    print("\nBrowsing %d service(s), press Ctrl-C to exit...\n" %
          len(services))
    browser = ServiceBrowser(zeroconf,
                             services,
                             handlers=[on_service_state_change])

    try:
        while True:
            sleep(0.1)
    except KeyboardInterrupt:
        pass
    finally:
        zeroconf.close()
def parse_zeroconf_devices(zc, listener):
    """ Manages the Zeroconf listeners and parse the existing broadcasted services

    :param nb_id: nuvlabox id
    :param nb_version: nuvlabox version
    :param zc: zeroconf object
    :param listener: zeroconf listener instance
    :return: list of peripheral documents
    """

    service_types_available = set(ZeroconfServiceTypes.find())

    old_service_types = set(listener.listening_to) - service_types_available
    new_service_types = service_types_available - set(listener.listening_to)

    for new in new_service_types:
        listener.listening_to[new] = ServiceBrowser(zc, new, listener)

    for old in old_service_types:
        listener.listening_to[old].cancel()
        logging.info(f'Removing Zeroconf listener for service type {old}: {listener.listening_to.pop(old)}')

    return format_zeroconf_services(listener.all_info)
示例#12
0
    args = parser.parse_args()

    if args.debug:
        logging.getLogger('zeroconf').setLevel(logging.DEBUG)
    if args.v6:
        ip_version = IPVersion.All
    elif args.v6_only:
        ip_version = IPVersion.V6Only
    else:
        ip_version = IPVersion.V4Only

    zeroconf = Zeroconf(ip_version=ip_version)

    services = ["_http._tcp.local.", "_hap._tcp.local."]
    if args.find:
        services = list(ZeroconfServiceTypes.find(zc=zeroconf))

    print("\nBrowsing %d service(s), press Ctrl-C to exit...\n" %
          len(services))
    browser = ServiceBrowser(zeroconf,
                             services,
                             handlers=[on_service_state_change])

    try:
        while True:
            sleep(0.1)
    except KeyboardInterrupt:
        pass
    finally:
        zeroconf.close()
示例#13
0
        self.services[svctype][name] = svcinfo
        self.servers[name] = svctype
        note("+", svctype, name)

    def remove_service(self, zeroconf, svctype, name):
        self.services[svctype][name] = None
        note("-", svctype, name)


if __name__ == '__main__':

    zc = Zeroconf()
    listener = Listener()

    print("Detecting services...")
    services = ZeroconfServiceTypes.find(zc)
    print("{}: {}".format(len(services), ', '.join(services)))

    print("Detecting hosts...")
    for service in services:
        browser = ServiceBrowser(zc, service, listener)
    sleep(3)
    print("Found {}".format(len(listener.servers)))

    print()

    def escape(s):
        return s.decode().encode('unicode_escape').decode()

    with open("services.csv", "w") as fh:
        for service in services:
示例#14
0
from zeroconf import ZeroconfServiceTypes
print('\n'.join(ZeroconfServiceTypes.find()))
示例#15
0
# A quick study to learn a bit about the mDNS/Bonjour systems on my home network
# Much of this code was copied from https://github.com/jstasiak/python-zeroconf

logging.basicConfig(stream=sys.stdout, level=logging.INFO)
log = logging.getLogger()


class MyListener:
    def remove_service(self, zeroconf, type, name):
        print("Service %s removed" % (name, ))

    def add_service(self, zeroconf, type, name):
        info = zeroconf.get_service_info(type, name)
        print("Service %s added, service info: %s" % (name, info))


print("\n".join(ZeroconfServiceTypes.find()))

zeroconf = Zeroconf()
listener = MyListener()
browsers = []
for s in ZeroconfServiceTypes.find():
    if len(s.split(".")[0]) <= 15:
        print(f"browsing {s}")
        browsers.append(ServiceBrowser(zeroconf, s, listener))

try:
    input("Press enter to exit...\n\n")  # nosec
finally:
    zeroconf.close()
示例#16
0
            if callable(data):
                # https://stackoverflow.com/a/41188411/8608146
                sig = signature(data)
                params = sig.parameters

                if len(params) == 0:
                    print(x, ":", data())

            else:
                print(x, ":", data)


# print(get_all_addresses())
# print(get_local_ip())

print(ZeroconfServiceTypes.find())

zeroconf = Zeroconf()

# register a service
zeroconf.register_service(
    ServiceInfo(
        "_coolapp._udp.local.",
        "{}._coolapp._udp.local.".format(f"pc-{random.randint(0, 255)}"),
        socket.inet_aton(get_local_ip()),
        find_free_port(),
        0,
        0,
        # this is the txt record
        properties={"data": "device"}))
示例#17
0
 def cmd_list(self):
     print( '\n'.join(ZeroconfServiceTypes.find() ) )