def setup(hass, config):
    """Setup component."""
    last_trigger = dt_util.now()
    netgear = Netgear(password='******')

    def check_netgear(_=None):
        now = dt_util.now()

        if hass.states.get('group.tracker').state == 'home' or (
                now - hass.states.get('group.tracker').last_updated
        ) < datetime.timedelta(hours=1):
            _LOGGER.error("Netgear reboot home")
            return

        nonlocal last_trigger
        if now - last_trigger < datetime.timedelta(hours=30):
            _LOGGER.error("Netgear reboot %s", now - last_trigger)
            return

        res = netgear.reboot()
        _LOGGER.error("Netgear reboot %s", res)
        last_trigger = dt_util.now()

    track_time_change(hass,
                      check_netgear,
                      second=22,
                      minute=6,
                      hour=[2, 4, 9, 13])
    return True
Esempio n. 2
0
    def __init__(
        self,
        host,
        ssl,
        username,
        password,
        port,
        devices,
        excluded_devices,
        accesspoints,
    ):
        """Initialize the scanner."""

        self.tracked_devices = devices
        self.excluded_devices = excluded_devices
        self.tracked_accesspoints = accesspoints

        self.last_results = []
        self._api = Netgear(password, host, username, port, ssl)

        _LOGGER.info("Logging in")

        results = self.get_attached_devices()

        self.success_init = results is not None

        if self.success_init:
            self.last_results = results
        else:
            _LOGGER.error("Failed to Login")
Esempio n. 3
0
def main():
    netgear = Netgear(password=get_router_admin_password())
    upload_queue = queue.Queue()
    download_queue = queue.Queue()

    cumulative_upload = 0
    cumulative_download = 0
    duration = 1
    init_upload, init_download = get_today_upload_and_download(netgear)
    upload_queue.put(init_upload)
    download_queue.put(init_download)

    while True:
        time.sleep(1)
        new_upload, new_download = get_today_upload_and_download(netgear)
        upload_queue.put(new_upload)
        download_queue.put(new_download)
        if duration < 10:
            duration += 1
        else:
            init_upload = upload_queue.get()
            init_download = download_queue.get()

        upload_rate = (new_upload - init_upload) / duration
        download_rate = (new_download - init_download) / duration

        print("Upload Rate: ", '%.3f' % (upload_rate * 1024),
              "KB,\tDownload Rate: ", '%.3f' % (download_rate), "MB")
def get_scanner(hass, config):
    """Validate the configuration and returns a Netgear scanner."""
    info = config[DOMAIN]
    host = info[CONF_HOST]
    ssl = info[CONF_SSL]
    username = info[CONF_USERNAME]
    password = info[CONF_PASSWORD]
    port = info.get(CONF_PORT)
    devices = info[CONF_DEVICES]
    excluded_devices = info[CONF_EXCLUDE]
    accesspoints = info[CONF_APS]

    api = Netgear(password, host, username, port, ssl)
    scanner = NetgearDeviceScanner(api, devices, excluded_devices,
                                   accesspoints)

    _LOGGER.debug("Logging in")

    results = scanner.get_attached_devices()

    if results is not None:
        scanner.last_results = results
    else:
        _LOGGER.error("Failed to Login")
        return None

    return scanner
Esempio n. 5
0
def main():
    netgear = Netgear(password=get_router_admin_password())
    config_devices = check(get_config_devices(), get_attached_devices(netgear))

    for device in config_devices:
        if device.is_attached:
            print(device.label + ": Online")
        else:
            print(device.label + ": Offline")
Esempio n. 6
0
def get_netgear_devices():
    netgear_key = os.environ['netgear_key']
    netgear = Netgear(password=netgear_key)

    res_dict = []
    for i in netgear.get_attached_devices():
        temp_dict = dict(zip(i._fields, list(i)))
        temp_dict['date'] = datetime.isoformat(datetime.now())
        res_dict.append(temp_dict)

    return pd.DataFrame.from_dict(res_dict)
Esempio n. 7
0
def main():
    """Scan for devices and print results."""
    netgear = Netgear(*sys.argv[1:])

    devices = netgear.get_attached_devices()

    if devices is None:
        print("Error communicating with the Netgear router")

    else:
        for i in devices:
            print(i)
Esempio n. 8
0
def get_api(
    password: str,
    host: str = None,
    username: str = None,
    port: int = None,
    ssl: bool = False,
) -> Netgear:
    """Get the Netgear API and login to it."""
    api: Netgear = Netgear(password, host, username, port, ssl)

    if not api.login():
        raise CannotLoginException

    return api
Esempio n. 9
0
def ValidatePARMS():
    global GPIOpinsC
    cntlINI.read('CONTROL.ini')  # Controllers
    cntlGPIO.read('GPIO.ini')  # GPIO settings

    # If netgear set allow access to Netgear Router
    if "netgear" in cntlINI["SETTINGS"]:
        SendMSG("NetGear Active")
        netgear = Netgear(password=cntlINI["SETTINGS"]["netgear"])
        if 'OWNER' in cntlINI:
            Router = True
            for sfld in cntlINI["OWNER"]:
                print(cntlINI["OWNER"][sfld])

    # ZigBee controllers
    if cntlINI["ZIGBEE"]["key"] == '':
        SendMSG("ZigBee Key Missing ")
        return True

    SendMSG("ZigBee " + str(cntlINI["ZIGBEE"]["ip"]) + " : " +
            str(cntlINI["ZIGBEE"]["key"]))
    GPIOpinsC = GPIOpins(cntlGPIO)

    return False
Esempio n. 10
0
def getlogdata(password=""):
    from pynetgear import Netgear
    import datetime

    # Instantiate the netgear api connection
    netgear = Netgear(password=password)

    # Open the log files - create if needed
    uploadlog = open("netgear_upload.log", "a+")
    downloadlog = open("netgear_download.log", "a+")

    # Look for the previous value from the file, if there isn't one then set it to zero
    uploadprev = uploadlog.readlines()
    if len(uploadprev) > 0:
        uploadprev = uploadprev[-1].split(",")[0]
    else:
        uploadprev = 0
    downloadprev = downloadlog.readlines()
    if len(downloadprev) > 0:
        downloadprev = downloadprev[-1].split(",")[0]
    else:
        downloadprev = 0

    # The previous value from the file will be a string, we need a float to do math with
    uploadprev = float(uploadprev)
    downloadprev = float(downloadprev)

    # Get the traffic meter data via the api
    traffic = netgear.get_traffic_meter()
    upload = traffic.get("NewTodayUpload")
    download = traffic.get("NewTodayDownload")

    # If the previous value is less than the current value, subtract it.  Otherwise it is either
    # - a new log run so don't subtract or
    # - it is a new day, so we will use yesterdays total to figure it out
    if upload >= uploadprev:
        uploadvalue = upload - uploadprev
    else:
        if uploadprev == 0:
            uploadvalue = upload
        else:
            uploadvalue = upload
            #The router doesn't log yesterday right, it seems to be less than prev
            #uploadvalue = (traffic.get("NewYesterdayUpload") - uploadprev) + upload
    if download >= downloadprev:
        downloadvalue = download - downloadprev
    else:
        if downloadprev == 0:
            downloadvalue = upload
        else:
            downloadvalue = upload
            #The router doesn't log yesterday right, it seems to be less than prev
            #downloadvalue = (traffic.get("NewYesterdayDownload") - uploadprev) + upload

    # Get the time and add the lines to the log files
    now = datetime.datetime.now()
    uploadlog.writelines("%f,%s,%f\n" % (upload, now, uploadvalue))
    downloadlog.writelines("%f,%s,%f\n" % (download, now, downloadvalue))

    # Close the log files
    uploadlog.close()
    downloadlog.close()

    #send the data to the google sheet for graphing
    output_to_gsheet([[str(now), downloadvalue, uploadvalue]])
Esempio n. 11
0
import config
import pandas as pd
from pandas.io import sql
import MySQLdb
from pynetgear import Netgear
import os
from datetime import datetime

seb_mysql_key = os.environ['seb_mysql_key']

con = MySQLdb.connect('localhost', 'seb', seb_mysql_key)

netgear_key = os.environ['netgear_key']
netgear = Netgear(password=netgear_key)

res_dict = []
for i in netgear.get_attached_devices():
    temp_dict = dict(zip(i._fields, list(i)))
    temp_dict['date'] = datetime.isoformat(datetime.now())
    res_dict.append(temp_dict)

A = pd.DataFrame.from_dict(res_dict)

# A.to_sql(con=con, name='table_name_for_df', if_exists='replace', flavor='mysql')
Esempio n. 12
0
#!/usr/bin/env python3

# NOTE: this example requires PyAudio because it uses the Microphone class

import speech_recognition as sr
from pynetgear import Netgear
from phue import Bridge

def setLights(lights, setOn):
	for light in lights:
		light.on = setOn
		
hueMac = 'MAC_HUE_BRIDGE'
BING_KEY = "BING_API_KEY" # Microsoft Bing Voice Recognition API keys 32-character lowercase hexadecimal strings

netgear = Netgear('password')

hueIp = -1

print 'Connecting to router. Devices found:'
for device in netgear.get_attached_devices():
	print device
	if device.mac == hueMac:
		hueIp = device.ip

if hueIp == -1:
	print 'Hue not found, aborting..'
	exit
else:
	print 'Hue found at ' + hueIp
Esempio n. 13
0
from pynetgear import Netgear
from lockControl import LockControl
#from smartSwitchControl import SmartSwitchControl
from astral import Astral
from subprocess import Popen, PIPE, call
import os, time, datetime, threading, json, simplejson, pytz

netgear = Netgear(password = "******")
#switches = SmartSwitchControl()
lock = LockControl()
knownHosts = []
seenHosts = []

class OccDetectionControl():

	#Seems unnecessary but leaving for call if needed, has no change verification pause
	def createLog(self, entry):
		log = open("./results/houseLogConfirmed.txt", "a+")
		time = datetime.datetime.now()
		log.write(entry + "- " + time.strftime("%A, %b %d, %Y") + " @ " + time.strftime("%I:%M:%S %p") + "\n")

	#Better representation to check if skipped out host really changed
	def createConfirmedLog(self, confirmedHosts):
		log = open("./results/houseLogConfirmed.txt", "a+")
		time = datetime.datetime.now()
		log.write(confirmedHosts + "- " + time.strftime("%A, %b %d, %Y") + " @ " + time.strftime("%I:%M:%S %p") + "\n")

	def findPresentHosts(self):
		while True:
			try:
				global knownHosts
Esempio n. 14
0
    print("Getting attached devices...")
    devices = netgear.get_attached_devices()
    print("Done.")
    print("Getting traffic meter...")
    traffic = netgear.get_traffic_meter()
    print("Done.")
    print("Writing to logs...")
    write_logs(devices, traffic)
    print("Done.")
    print("Waiting for 1 hour before starting again.")
    threading.Timer(3600, logs_start).start()


print("Logging into Netgear.")
netgear = Netgear(password=data['router-password'],
                  host=data['host-ip'],
                  port=data['port'])
# print(netgear.get_traffic_meter())
print("Logged in...")

print("Getting attached devices...")
devices = netgear.get_attached_devices()
print("Done.")
print("Getting traffic meter...")
traffic = netgear.get_traffic_meter()
print("Done.")
print("Writing to logs...")

print('Setting up logs...')
with open('data.csv', 'a+') as csvfile:
    writer = csv.writer(csvfile)
Esempio n. 15
0
from flask import Flask, render_template
import requests
from requests.auth import HTTPBasicAuth
from html.parser import HTMLParser
import time
import datetime
import re
import json
import argparse

from pynetgear import Netgear
import threading
import os
import sys, traceback

netgear = Netgear(password=os.environ['ROUTER_ADMIN_PASSWORD'])

app = Flask(__name__, static_url_path='', static_folder='./')

__router_status = {}
__last_updated = None
__started_time = datetime.datetime.now()
__traffic_last_updated = datetime.datetime.now()
__traffic = {}
__devices = []
__stop = False


def datetime_handler(x):
    if isinstance(x, datetime.datetime):
        return x.isoformat()
from pynetgear import Netgear
import config as cfg

netgear = Netgear(host=cfg.host, password=cfg.password)

ignore_devices = cfg.ignore_devices
user_devices = []

attached_devices = netgear.get_attached_devices()

for device in attached_devices:
    if device.mac not in ignore_devices:
        user_devices.append(device.mac)

print(user_devices)