コード例 #1
0
def list_available_devices() -> list:
    """
    Method to return list of available device names on the network
    """
    devices = upnpclient.discover()

    return [d.friendly_name for d in devices]
コード例 #2
0
 def discovery(timeout=5):
     out = {}
     try:
         _LOGGER.info("Searching upnp devices")
         devs = upnpclient.discover(timeout=5)
         _LOGGER.info("Found " + str(len(devs)) + " upnp devices")
         rc = {
             "RenderingControl": DeviceUpnpIRRC,
             "MainTVAgent2": DeviceUpnpIRTA2
         }
         for d in devs:
             u = upar(d.location)
             for k, v in rc.items():
                 if k in d.service_map:
                     _LOGGER.info("Found " + k + " at " + d.location)
                     hp = (u.hostname, u.port)
                     m = '{}:{}:'.format(*hp) + k
                     out[m] = v(hp=hp,
                                mac=m,
                                name='',
                                location=d.location,
                                deviceobj=d)
     except:  # noqa: E722
         _LOGGER.warning(f"{traceback.format_exc()}")
     return out
コード例 #3
0
async def discover(ctx):
    """Discover supported devices."""
    TIMEOUT = 3
    debug = 0
    if ctx.obj:
        debug = ctx.obj["debug"] or 0
    click.echo("Discovering for %s seconds" % TIMEOUT)
    devices = upnpclient.discover(TIMEOUT)
    for dev in devices:
        if "ScalarWebAPI" in dev.service_map:
            if debug:
                print(
                    etree.tostring(dev._root_xml, pretty_print=True).decode())
            model = dev.model_name
            model_number = dev.model_number

            pretty_name = "%s - %s" % (model, model_number)

            root = objectify.fromstring(etree.tostring(dev._root_xml))
            device = root["device"]
            info = device["{urn:schemas-sony-com:av}X_ScalarWebAPI_DeviceInfo"]
            endpoint = info["X_ScalarWebAPI_BaseURL"].text
            version = info["X_ScalarWebAPI_Version"].text
            services = info["X_ScalarWebAPI_ServiceList"].iterchildren()

            click.echo(click.style("Found %s" % pretty_name, bold=True))
            click.echo("* API version: %s" % version)
            click.echo("* Endpoint: %s" % endpoint)

            click.echo("* Services:")
            for serv in services:
                click.echo("  - Service: %s" % serv.text)
コード例 #4
0
def main():
    router = None
    while router == None:
        print("upnp discover looking for router")
        devices = upnpclient.discover()
        print(devices)
        for device in devices:
            print(device)
            print(device.model_name)
            if device.model_name == 'rt4230w-d187 router':
                router = device
                print("upnp router found")
                break
        print("upnp router not found, retrying")
    print("starting prom metrics http server on port %s", PROM_HTTP_PORT)
    start_http_server(PROM_HTTP_PORT)

    print("main metrics collection loop")
    while True:
        time.sleep(1)
        conn_status = router.WANIPConn1.GetStatusInfo()
        router_connection_uptime.set(conn_status.get('NewUptime', -1))
        if conn_status.get('NewConnectionStatus', '') == 'Connected':
            router_connection_status.set(1)
        else:
            router_connection_status.set(0)
        router_bytes_sent.set(router.WANCommonIFC1.GetTotalBytesSent().get('NewTotalBytesSent', -1))
        router_bytes_received.set(router.WANCommonIFC1.GetTotalBytesReceived().get('NewTotalBytesReceived', -1))
        router_packets_sent.set(router.WANCommonIFC1.GetTotalPacketsSent().get('NewTotalPacketsSent', -1))
        router_packets_received.set(router.WANCommonIFC1.GetTotalPacketsReceived().get('NewTotalPacketsReceived', -1))
コード例 #5
0
def Port_forwarding():
    try:
        devices = upnpclient.discover()
        status = devices[0].WANIPConn1.GetStatusInfo()
        if status['NewConnectionStatus'] != 'Connected':
            for i, x in enumerate(devices):
                status = x.WANIPConn1.GetStatusInfo()
                if status == 'Connected':
                    d = devices[i]
                    break
        else:
            d = devices[0]
        d.WANIPConn1.AddPortMapping(
            NewRemoteHost='0.0.0.0',
            NewExternalPort=port,
            NewProtocol='TCP',
            NewInternalPort=port,
            NewInternalClient=host,
            NewEnabled='1',
            NewPortMappingDescription='P2P',
            NewLeaseDuration=10000)
        print('Forwarding Success!!!')
        return True
    except:
        print('Device not found')
        return False
コード例 #6
0
ファイル: __init__.py プロジェクト: malekbr/mycroft-hue
    def _attempt_connection(self):
        """
        This will attempt to connect to the bridge,
        but will not handle any errors on it's own.

        Raises
        ------
        UnauthorizedUserException
            If self.username is not None, and is not registered with the bridge
        """
        if self.user_supplied_ip:
            self.ip = self.settings.get('ip')
        else:
            device = next(filter(lambda device : "Philips hue" in device.model_name, upnpclient.discover()))
            self.ip = urllib.parse.urlparse(device.location).hostname
        if self.username:
            url = 'http://{ip}/api/{user}'.format(ip=self.ip,
                                                  user=self.username)
            data = get(url).json()
            data = data[0] if isinstance(data, list) else data
            error = data.get('error')
            if error:
                description = error.get('description')
                if description == "unauthorized user":
                    raise UnauthorizedUserException(self.username)
                else:
                    raise Exception('Unknown Error: {0}'.format(description))

        self.bridge = Bridge(self.ip, self.username)
コード例 #7
0
 def __init__(self, main_port=8000, timeout=2):
     log.info("UPnP Passthrough Service Started.")
     log.debug("Fetching a device list...")
     self.dev_list = upnpclient.discover(timeout)
     log.debug(f"Fetch finished in {timeout}s")
     log.debug(f"Devices detected: {self.dev_list}")
     if not self.dev_list:
         log.warning("No UPnP Devices was found. Stopping NatWorker...")
         del self
コード例 #8
0
def discover_igd():
    devices = upnpclient.discover()
    igd_devices = list(filter(lambda d: d.device_type in IGD, devices))
    logger.debug("IGD devices: %s", igd_devices)
    if len(igd_devices) != 1:
        raise SystemExit()
    igd = igd_devices.pop()

    return igd
コード例 #9
0
ファイル: upnp.py プロジェクト: gfediere/SiCKRAGE-1
    def _discover_upnp_device(self):
        devices = upnpclient.discover()
        if devices:
            for device in devices:
                try:
                    device.WANIPConn1
                except AttributeError:
                    continue

                return device
コード例 #10
0
ファイル: upnp.py プロジェクト: SiCKRAGETV/SiCKRAGE
    def _discover_upnp_device(self):
        devices = upnpclient.discover()
        if devices:
            for device in devices:
                try:
                    device.WANIPConn1
                except AttributeError:
                    continue

                return device
コード例 #11
0
def discover_hue(**kwargs):
    cloud = kwargs.get("cloud", False)
    upnp = kwargs.get("upnp", True)

    bridges = Bridge.select()

    bridge_addresses = []
    for bridge in bridges:
        bridge_addresses.append(bridge.ip)

    if cloud:
        devices_resp = requests.get("https://discovery.meethue.com/")

        if devices_resp.status_code == 200:
            devices = devices_resp.json()
            for device in devices:
                ip_address = device.get("internalipaddress")
                urlbase = "http://%s:80" % ip_address
                debug_address = "%s/debug/clip.html" % urlbase

                if ip_address not in bridge_addresses:
                    new_bridge = Bridge.create(
                        name="Philips Hue Bridge",
                        ip=ip_address,
                        serial_number=device.get("id"),
                        url=urlbase,
                        debug=debug_address,
                        device_id=device.get("id"),
                    )
                    bridge_addresses.append(ip_address)

    if upnp:
        devices = upnpclient.discover()
        for device in devices:
            if "Philips hue" in device.friendly_name:
                urlbase = device.location.replace("/description.xml", "")
                ip_address = re.search(r"(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})",
                                       urlbase).group(1)
                debug_address = "%s/debug/clip.html" % urlbase

                if ip_address not in bridge_addresses:
                    new_bridge = Bridge.create(
                        name=device.friendly_name,
                        ip=ip_address,
                        serial_number=device.serial_number,
                        url=urlbase,
                        debug=debug_address,
                        device_id=device.serial_number,
                    )
                    bridge_addresses.append(ip_address)

    bridges = Bridge.select()

    return bridges
コード例 #12
0
def getDevicesWithDefault(deviceURL):
    global cachedDevices
    startIfNeeded()
    if deviceURL:
        devices = [upnpclient.Device(deviceURL)]
    else:
        if not cachedDevices:
            #Very quick scan because we let the background thread handle the slow stuff.
            cachedDevices = upnpclient.discover(timeout=1)
        devices = cachedDevices
    return devices
コード例 #13
0
ファイル: handleupnp.py プロジェクト: EternityForest/drayer
def getWANAddresses():
    devices = upnpclient.discover()
    addresses = []

    for i in devices:
        for j in i.services:
            for k in j.actions:
                if k.name == "GetExternalIPAddress":
                    if "WAN" in j.service_type:
                        addresses.append(
                            j.GetExternalIPAddress()["NewExternalIPAddress"])
    return addresses
コード例 #14
0
 def test_discover(self, mock_scan, mock_server):
     """
     discover() should call netdisco's scan function and return a list of unique servers.
     """
     url = 'http://www.example.com'
     entry = mock.Mock()
     entry.location = url
     mock_scan.return_value = [entry, entry]
     ret = upnp.discover()
     mock_scan.assert_called()
     mock_server.assert_called_with(url)
     self.assertEqual(ret, ['test string'])
コード例 #15
0
 def test_discover_exception(self, mock_scan, mock_server):
     """
     If unable to read a discovered server's root XML file, it should not appear in the list.
     """
     url = 'http://www.example.com'
     entry = mock.Mock()
     entry.location = url
     mock_scan.return_value = [entry]
     ret = upnp.discover()
     mock_scan.assert_called()
     mock_server.assert_called_with(url)
     self.assertEqual(ret, [])
コード例 #16
0
ファイル: discover.py プロジェクト: krisek/audioloader
def discover_players():
    players = {}
    others = {}
    devices = upnpclient.discover()

    for d in devices:

        services_s = map(lambda service: str(service), d.services)
        ip = ipaddress.ip_network('200.200.200.200/32')
        ip_text = ''
        m = re.search('^http://([^\/\:]+)', d._url_base)
        if m:
            ip = ipaddress.ip_network(m.group(1))
            ip_text = m.group(1)
        if ip.subnet_of(
                local_net
        ) and "<Service service_id='urn:upnp-org:serviceId:AVTransport'>" in services_s:

            players[d.location] = {
                'location': d.location,
                'ip': ip_text,
                'name': d.friendly_name,
                'model_name': d.model_name,
                'last_seen': time.time()
            }

            try:
                r = redis.Redis(host='localhost',
                                port=6379,
                                db=0,
                                decode_responses=True)
                r.set('upnp:player:' + d.location + ':data',
                      json.dumps(players[d.location]))
                r.set('upnp:player:' + d.location + ':last_seen',
                      players[d.location]['last_seen'])
            except Exception as e:
                logging.warning('setting data in redis nok ' + str(e))
                logging.debug(traceback.format_exc())
            finally:
                del r

        else:
            others[d.location] = {
                'location': d.location,
                'ip': ip_text,
                'name': d.friendly_name,
                'model_name': d.model_name,
                'last_seen': time.time()
            }

    return (players, others)
コード例 #17
0
def setup_port_map(
    port: int,
    duration: int = DEFAULT_PORTMAP_DURATION
) -> Tuple[AnyIPAddress, AnyIPAddress]:
    """
    Set up the port mapping

    :return: the IP address of the new mapping (or None if failed)
    """
    devices = upnpclient.discover()
    if not devices:
        raise PortMapFailed("No UPnP devices available")

    for upnp_dev in devices:
        try:
            internal_ip, external_ip = _setup_device_port_map(
                upnp_dev, port, duration)
            logger.info(
                "NAT port forwarding successfully set up: internal=%s:%d external=%s:%d",
                internal_ip,
                port,
                external_ip,
                port,
            )
            break
        except _NoInternalAddressMatchesDevice:
            logger.debug(
                "No internal addresses were managed by the UPnP device at %s",
                upnp_dev.location,
            )
            continue
        except _WANServiceNotFound:
            logger.debug(
                "No WAN services managed by the UPnP device at %s",
                upnp_dev.location,
            )
            continue
        except PortMapFailed:
            logger.debug(
                "Failed to setup portmap on UPnP divec at %s",
                upnp_dev.location,
                exc_info=True,
            )
            continue
    else:
        logger.info("Failed to setup NAT portmap.  Tried %d devices",
                    len(devices))
        raise PortMapFailed(
            f"Failed to setup NAT portmap.  Tried {len(devices)} devices.")

    return ipaddress.ip_address(internal_ip), ipaddress.ip_address(external_ip)
コード例 #18
0
ファイル: evilproxy.py プロジェクト: raymondmorsman/UCD
def punchHole(ip, eport, oport):
    upnpdevices = upnpclient.discover()
    firstdevice = upnpdevices[0]  # assume only one
    firstdevice.WANIPConn1.AddPortMapping(
        NewRemoteHost='0.0.0.0',
        NewExternalPort=oport,
        NewProtocol='TCP',
        NewInternalPort=eport,
        NewInternalClient=ip,
        NewEnabled='1',
        NewPortMappingDescription='Дмитрий was here',
        NewLeaseDuration=84600)
    print('Forwarding is enabled')
    return ()
コード例 #19
0
ファイル: main.py プロジェクト: pedrocicoleme/dlnactl
def available_devices():
    """
    List all devices that are AVTransport media renderers
    """
    devices = []

    for device in upnpclient.discover():
        for service in device.services:
            if service.service_id == AVTRANSPORT_SERVICE_ID:
                logger.info(service.actions)

                devices.append(device)

    return devices
コード例 #20
0
ファイル: handleupnp.py プロジェクト: EternityForest/drayer
def addMapping(port, proto, desc="Description here"):
    """Returns a list of Mapping objects"""
    devices = upnpclient.discover()
    mappings = []

    for i in devices:
        l = urlparse(i.location).netloc
        if ":" in l:
            l = l.split(":")[0]

        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM,
                          socket.IPPROTO_UDP)
        s.connect((l, 12345))

        #Get the IP that we use to talk to that particular router
        ownAddr = s.getsockname()[0]
        s.close()
        del s

        for j in i.services:
            for k in j.actions:
                if k.name == "GetExternalIPAddress":
                    if "WAN" in j.service_type:

                        def clean():
                            j.DeletePortMapping(
                                NewRemoteHost="0.0.0.0",
                                NewExternalPort=port,
                                NewProtocol=proto,
                            )

                        with listlock:
                            cleanuplist.append(clean)

                        def renew():
                            j.AddPortMapping(NewRemoteHost='0.0.0.0',
                                             NewExternalPort=port,
                                             NewProtocol=proto,
                                             NewInternalPort=port,
                                             NewInternalClient=ownAddr,
                                             NewEnabled='1',
                                             NewPortMappingDescription=desc,
                                             NewLeaseDuration=3600)

                        renew()
                        with listlock:
                            renewlist.append(renew)
                        mappings.append(Mapping(clean, renew))
    return mappings
コード例 #21
0
def search_igd_port_actions():
    # search for devices which has WANIPConn1.AddPortMapping
    devices = upnpclient.discover(7)
    igd_actions = []
    for router in [
            device for device in devices
            if Environment().default_gateway in device.location
    ]:
        for service in router.services:
            for action in service.actions:
                if "AddPortMapping" in action.name and not not_in(
                        igd_actions, action):
                    igd_actions.append(action)

    return igd_actions
コード例 #22
0
def upnp_add_port_mapping(internal_port: int, external_port: int, ip: str, name: str):
    devices = upnpclient.discover()

    for d in devices:
        if hasattr(d, "WANIPConn1"):
            print(d.WANIPConn1.GetStatusInfo())

            d.WANIPConn1.AddPortMapping(
                NewRemoteHost="",
                NewExternalPort=external_port,
                NewProtocol='TCP',
                NewInternalPort=internal_port,
                NewInternalClient=ip,
                NewEnabled='1',
                NewPortMappingDescription=name,
                NewLeaseDuration=0)
コード例 #23
0
def modem_bilgisi():
    import upnpclient
    devices = upnpclient.discover()
    #print(devices)
    if len(devices) > 0:
        d = devices[0]
        sonuc = "upnp"
        marka = d.manufacturer
        model = d.model_name
        model_numarası = d.model_number
        modem_serinumarası = d.serial_number
        return sonuc, marka, model, model_numarası, modem_serinumarası
    else:
        return "not_upnp", "marka", "model", "model_numarası", "modem_serinumarası"


#print(modem_bilgisi())
コード例 #24
0
def renewer():
    global cachedDevices
    while 1:
        #This takes such a long time that I can't think of a better way,
        #Aside from a background rescan
        try:
            cachedDevices = upnpclient.discover()
            listMappings()
        except:
            logger.exception("err")
        time.sleep(8*60)
        try:
            with listlock:
                for i in renewlist:
                    i()
        except Exception as e:
            print(e)
コード例 #25
0
def discover_ip(device_name) -> str:
    """
    Method to return the URL (IP) to send requests to for a roku device of
    the given name
    :param device_name: Name of device we are searching for
    :return: An IP address string that can be used to send requests
    :raises: ValueError if no such device is found
    """
    devices = upnpclient.discover()

    roku_device = [
        d for d in devices if device_name.lower() == d.friendly_name.lower()
    ]

    if len(roku_device) == 0:
        raise ValueError(f'No device found for name {device_name}')

    return roku_device[0].location
コード例 #26
0
ファイル: PunchPort.py プロジェクト: fake-name/WebRequest
    def _init_upnp(self):
        devices = upnpclient.discover()
        self.log.info("Found %s UPnP devices on LAN", len(devices))

        for device in devices:
            try:
                _ = device.WANIPConn1
                self.gateway_device = device
                self.log.info("Found gateway device: %s", device)
            except Exception:
                pass

        if not self.gateway_device:
            raise exc.CouldNotFindUpnpGateway(
                "No UPnP Gateway found. Found %s UPnP devices on LAN" %
                len(devices))

        self.log.info("Resolved WAN address: %s", self.get_wan_ip())
コード例 #27
0
def start_yoga_paused():
    time.sleep(60)
    devices = upnpclient.discover()
    xbox = [
        d for d in devices if d.friendly_name == 'VANGUARD'
        and d.model_description == 'Digital Media Renderer'
    ][0]
    service = [
        s for s in xbox.services
        if s.service_type == 'urn:schemas-upnp-org:service:AVTransport:1'
    ][0]
    index = get_day_number() % len(yoga_videos)
    print(get_day_number(), index)
    uri = dlna_server_uri + yoga_videos[index]
    print(uri)
    service.SetAVTransportURI(InstanceID=0,
                              CurrentURI=uri,
                              CurrentURIMetaData="")
    time.sleep(5)
    service.Pause(InstanceID=0)
    return "Started yoga video"
コード例 #28
0
    def run(self,
            internal_port=8192,
            external_port=8192,
            duration=0,
            protocol="TCP",
            name="Internet access",
            enabled="1",
            internal_ip=gethostbyname(gethostname()),
            **kwargs):
        from ipaddress import ip_address
        try:
            addr = ip_address(internal_ip)
            if addr.is_loopback:
                raise ValueError("Address can not be loopback!")

        except ValueError as e:
            raise ValueError("Internal IP address is invalid: {}".format(e))

        import upnpclient
        devices = upnpclient.discover()
        success = 0

        for x in devices:
            if self._run.is_set():
                try:
                    x.WANIPConn1.AddPortMapping(NewRemoteHost="0.0.0.0",
                                                NewExternalPort=external_port,
                                                NewProtocol=protocol,
                                                NewInternalPort=internal_port,
                                                NewInternalClient=internal_ip,
                                                NewEnabled=enabled,
                                                NewPortMappingDescription=name,
                                                NewLeaseDuration=duration)
                    success = success + 1
                except Exception:  # noqa
                    pass
            else:
                break
        return success > 0
コード例 #29
0
ファイル: upnp.py プロジェクト: alvarogf97/Audit
def upnp_devices_information():
    result = dict()
    result["status"] = True
    result["data"] = []
    devices = upnpclient.discover(5)
    for device in devices:
        device_json = dict()
        device_json["location"] = device.location
        device_json["name"] = device.friendly_name
        device_json["services"] = []
        for service in device.services:
            service_json = dict()
            service_json["id"] = service.service_id
            service_json["actions"] = []
            for action in service.actions:
                action_json = dict()
                action_json["name"] = action.name
                action_json["args_in"] = parse_args(action.argsdef_in)
                action_json["args_out"] = parse_args(action.argsdef_out)
                action_json["url"] = device.location
                service_json["actions"].append(action_json)
            device_json["services"].append(service_json)
        result["data"].append(device_json)
    return result
コード例 #30
0
ファイル: upnp.py プロジェクト: Red-Eyed/test
#!/usr/bin/env python3
import socket

import upnpclient


def get_local_ip():
    with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
        s.connect(("8.8.8.8", 80))
        return s.getsockname()[0]


if __name__ == '__main__':
    devices = upnpclient.discover()
    print(devices)

    d = devices[0]
    print(d.WANIPConn1.GetStatusInfo())

    d.WANIPConn1.AddPortMapping(
        NewRemoteHost='',
        NewExternalPort=60000,
        NewProtocol='TCP',
        NewInternalPort=60000,
        NewInternalClient=get_local_ip(),
        NewEnabled='1',
        NewPortMappingDescription='file_server',
        NewLeaseDuration=0)
コード例 #31
0
 def discover():
     SSDP.devices = upnpclient.discover()
     # print(SSDP.get_devices())
     ssdp_daemon = thd.Timer(30, SSDP.discover)
     ssdp_daemon.setDaemon(True)
     ssdp_daemon.start()