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")
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)
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)
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
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
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 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")
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
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
class NetgearDeviceScanner(DeviceScanner): """Queries a Netgear wireless router using the SOAP-API.""" 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") def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self._update_info() devices = [] for dev in self.last_results: tracked = (not self.tracked_devices or dev.mac in self.tracked_devices or dev.name in self.tracked_devices) tracked = tracked and (not self.excluded_devices or not (dev.mac in self.excluded_devices or dev.name in self.excluded_devices)) # when link_rate is None this means the router still knows about # the device, but it is not in range. if tracked and dev.link_rate is not None: devices.append(dev.mac) if (self.tracked_accesspoints and dev.conn_ap_mac in self.tracked_accesspoints): devices.append(f"{dev.mac}_{dev.conn_ap_mac}") return devices def get_device_name(self, device): """Return the name of the given device or the MAC if we don't know.""" parts = device.split("_") mac = parts[0] ap_mac = None if len(parts) > 1: ap_mac = parts[1] name = None for dev in self.last_results: if dev.mac == mac: name = dev.name break if not name or name == "--": name = mac if ap_mac: ap_name = "Router" for dev in self.last_results: if dev.mac == ap_mac: ap_name = dev.name break return f"{name} on {ap_name}" return name def _update_info(self): """Retrieve latest information from the Netgear router. Returns boolean if scanning successful. """ if not self.success_init: return _LOGGER.info("Scanning") results = self.get_attached_devices() if results is None: _LOGGER.warning("Error scanning devices") self.last_results = results or [] def get_attached_devices(self): """ List attached devices with pynetgear. The v2 method takes more time and is more heavy on the router so we only use it if we need connected AP info. """ if self.tracked_accesspoints: return self._api.get_attached_devices_2() return self._api.get_attached_devices()
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')
#!/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
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
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)
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)
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]])
import sys from pynetgear import Netgear 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)