예제 #1
0
    def init(self):
        """ Initialize the connection to the FRITZ!Box """
        self._fc = fritzconnection.FritzConnection(
            address=self._fritz_address, port=self._fritz_port,
            user=self._fritz_user)
        if self._fc.modelname is None:
            self._fc = None
            raise IOError("fritzcollectd: Failed to connect to %s" %
                          self._fritz_address)

        if not self._fc.call_action('WANIPConnection:1', 'GetStatusInfo'):
            self._fc = None
            raise IOError("fritzcollectd: Statusinformation via UPnP is "
                          "not enabled")

        self._filter_service_actions(self.SERVICE_ACTIONS,
                                     self._fc.actionnames)

        if self._fritz_password != '':
            self._fc_auth = fritzconnection.FritzConnection(
                address=self._fritz_address, port=self._fritz_port,
                user=self._fritz_user, password=self._fritz_password)
            try:
                self._fc_auth.call_action('WANIPConnection:1',
                                          'GetStatusInfo')

                self._filter_service_actions(self.SERVICE_ACTIONS_AUTH,
                                             self._fc_auth.actionnames)
            except XMLSyntaxError:
                self._fc = None
                self._fc_auth = None
                raise IOError("fritzcollectd: Incorrect password")
        else:
            collectd.info("fritzcollectd: No password configured, "
                          "some values cannot be queried")
예제 #2
0
 def __init__(self, host, user, passwd):
     self.host = host
     self.user = user
     self.passwd = passwd
     self.conn = fc.FritzConnection(address=self.host,
                                    user=self.user,
                                    password=self.passwd)
예제 #3
0
    def init(self):
        """ Initialize the connection to the FRITZ!Box """
        self._fc = fritzconnection.FritzConnection(
            address=self._fritz_address, port=self._fritz_port,
            user=self._fritz_user, password=self._fritz_password)
        if self._fc.modelname is None:
            self._fc = None
            raise IOError("fritzcollectd: Failed to connect to %s" %
                          self._fritz_address)

        if not self._fc.call_action('WANIPConn:1', 'GetStatusInfo'):
            self._fc = None
            raise IOError("fritzcollectd: Statusinformation via UPnP is "
                          "not enabled")

        if self._fritz_password != '':
            # If the 'Allow access for applications' option is disabled,
            # the connection behaves as if it was created without password.
            if 'WANIPConnection:1' not in self._fc.services.keys():
                self._fc = None
                raise IOError("fritzcollectd: Allow access for applications "
                              "is not enabled")

            try:
                self._fc.call_action('WANIPConnection:1', 'GetStatusInfo')
            except fritzconnection.AuthorizationError:
                self._fc = None
                raise IOError("fritzcollectd: Incorrect password or "
                              "'FRITZ!Box Settings' rights for user disabled")
        else:
            collectd.info("fritzcollectd: No password configured, "
                          "some values cannot be queried")

        self._filter_service_actions(self.SERVICE_ACTIONS,
                                     self._fc.actionnames)
 def __init__(self, host, port, username, password):
     # pylint: disable=import-error
     import fritzconnection as fc
     self._connection = fc.FritzConnection(address=host,
                                           port=port,
                                           user=username,
                                           password=password)
예제 #5
0
def main(unused_argv):
    if FLAGS.verbose:
        logging.set_verbosity(logging.DEBUG)
    if FLAGS.ipv6_hack:
        # TODO(pkern): Eliminate this. Right now socketserver is IPv4-only,
        # so what we should do is actually bring up a proper HTTP server and
        # then map the path. However to enable IPv6 listening this is an
        # awful hack of monkey-patching to make it work for now.
        import socketserver
        import socket
        socketserver.TCPServer.address_family = socket.AF_INET6
    client = fritzconnection.FritzConnection(
        address=FLAGS.address,
        user=FLAGS.username,
        password=FLAGS.password,
    )
    logging.info(
        f'Connection succeeded to {client.modelname} on {FLAGS.address}')
    actions = collect_actions(client)
    logging.info(f'Collected {len(actions)} actions')
    variables = collect_variables(client, actions)
    logging.info(f'Collected {len(variables)} variables')
    address, port = FLAGS.listen.rsplit(':', 1)
    start_wsgi_server(port=int(port), addr=address)
    logging.info(f'Listening on {FLAGS.listen}')
    for sig in (signal.SIGTERM, signal.SIGINT, signal.SIGHUP):
        signal.signal(sig, quit)
    exit.wait()
예제 #6
0
    def connect(self):
        logging.info("Connecting to Fritz!Box " + self.address + ":" + str(self.port) + " ...")
        self._connection = fritzconnection.FritzConnection(address = self.address, port = self.port, user = self.username, password = self.password)

        fritzboxLoopThread = threading.Thread(target=self._fritzboxLoop, name="fritzboxLoop")
        fritzboxLoopThread.start()
        self._threads.append(fritzboxLoopThread)
예제 #7
0
def main():
    '''Application entry point.'''

    args = parse_args()

    logging.basicConfig(
        format='%(asctime)-15s %(levelname)s: %(message)s',
        level=(logging.DEBUG if args.verbose else logging.INFO))

    settings = EnvSettingsResolver(SETTINGS_DESC)

    conn = fc.FritzConnection(address=settings.FRITZ_HOST,
                              user=settings.FRITZ_USER,
                              password=settings.FRITZ_PASS)

    results = []
    results.extend(process_all(conn))
    results.sort(key=lambda e: (e[0], e[1], e[2]))

    with open(args.csvfile, 'w', newline='') as fhdl:
        writer = csv.writer(fhdl)

        writer.writerow(['Service', 'Action', 'Attribute', 'Value'])

        for row in results:

            if args.data:
                writer.writerow(row)
            else:
                writer.writerow(row[0:3])

    logging.info(f'Wrote {len(results)} services / actions to {args.csvfile}.')
예제 #8
0
    def __init__(
        self,
        host,
        port,
        username,
        password,
        profile_on,
        profile_off,
        device_list,
    ):
        # pylint: disable=import-error
        import fritzconnection as fc
        from fritz_switch_profiles import FritzProfileSwitch

        self.connection = fc.FritzConnection(address=host,
                                             port=port,
                                             user=username,
                                             password=password)

        if device_list != DEFAULT_DEVICES:
            self.profile_switch = FritzProfileSwitch("http://" + host,
                                                     username, password)

        self.fritzstatus = fc.FritzStatus(fc=self.connection)
        self.ha_ip = get_local_ip()
        self.profile_on = profile_on
        self.profile_off = profile_off
        self.profile_last_updated = time.time()
        self.device_list = device_list

        self.username = username
        self.password = password
        self.port = port
        self.host = host
예제 #9
0
  def __init__(self, address=FRITZ_IP_ADDRESS, port=FRITZ_TCP_PORT):
    connection = fc.FritzConnection(address=address, port=port)
    print("Connected to FritzBox")

    self.connection = connection
    self.last_bytes_sent = self.bytes_sent 
    self.last_bytes_received = self.bytes_received
    self.last_traffic_call = time.time()
예제 #10
0
 def __init__(self, host, port, username, password, ha_ip):
     # pylint: disable=import-error
     import fritzconnection as fc
     self.connection = fc.FritzConnection(address=host,
                                          port=port,
                                          user=username,
                                          password=password)
     self.fritzstatus = fc.FritzStatus(fc=self.connection)
     self.ha_ip = ha_ip
예제 #11
0
def main():
    prefs = read_configuration(
        os.path.join(os.path.dirname(__file__), "fritz-speed.ini"))
    fc = fritzconnection.FritzConnection(address=prefs["fritz_ip"])

    status = fc.call_action("WANCommonIFC1", "GetAddonInfos")
    bytes_down = status["NewX_AVM_DE_TotalBytesReceived64"]
    bytes_up = status["NewX_AVM_DE_TotalBytesSent64"]

    update_rra(prefs["rra_filename"], str(bytes_up), str(bytes_down))
예제 #12
0
 def __init__(self,
              fc=None,
              address=fritzconnection.fritzconnection.FRITZ_IP_ADDRESS,
              port=fritzconnection.fritzconnection.FRITZ_TCP_PORT,
              user=fritzconnection.fritzconnection.FRITZ_USERNAME,
              password=''):
     super(FritzConnect, self).__init__()
     if fc is None:
         fc = fritzconnection.FritzConnection(address, port, user, password)
     self.fc = fc
예제 #13
0
 def __init__(self,
              fc=None,
              address=None,
              port=None,
              user=None,
              password=None):
     super(FritzHosts, self).__init__()
     if fc is None:
         fc = fritzconnection.FritzConnection(address, port, user, password)
     self.fc = fc
예제 #14
0
    def _fritzboxLoop(self):
        logging.debug("Starting Fritz!Box loop ...")

        while not self._stopEvent.is_set():
            for serviceName, serviceData in self.services.items():
                for actionName, actionData in serviceData['actions'].items():
                    try:
                        # Skip if period is not reached yet
                        if (('lastRun' in actionData) and ((time.time() - actionData['lastRun']) < actionData['period'])):
                            continue

                        logging.debug("Querying data for service: %s action %s ..." % (serviceName, actionName))
                        res = self._connection.call_action(serviceName, actionName)
                        for key, value in res.items():
                            # Skip keys not needed
                            if key not in actionData['values']:
                                continue

                            topic = serviceData['prefix']+key
                            if (key in actionData['values']) and ('topic' in actionData['values'][key]):
                                topic = (serviceData['prefix'] + actionData['values'][key]['topic']).format(
                                    id = serviceData['id'] if ('id' in serviceData) else ""
                                    )

                            if ('type' in actionData['values'][key]):
                                if (actionData['values'][key]['type'] == 'int'):
                                    value = int(value)
                                elif (actionData['values'][key]['type'] == 'float'):
                                    value = float(value)
                                elif (actionData['values'][key]['type'] == 'bool'):
                                    value = bool(value)
                                else:
                                    value = str(value)

                            if (('retain' in actionData['values'][key]) and (actionData['values'][key]['retain'] == 'true')):
                                retain = True
                            else:
                                retain = False                         

                            logging.debug('%s/%s/%s to %s: %r' % (serviceName, actionName, key, topic, value))

                            self._queue.put({'topic': topic, 'value': value, 'retain': retain})

                        actionData['lastRun'] = time.time()

                    except fritzconnection.fritzconnection.ServiceError as e:
                        logging.error("ServiceError: %r" % (e))
                        logging.info("Reconnecting to Fritz!Box " + self.address + ":" + str(self.port) + " ...")
                        self._connection = fritzconnection.FritzConnection(address = self.address, port = self.port, user = self.username, password = self.password)

                    except Exception as e:
                        logging.error("Exception: %r" % (e))

            self._stopEvent.wait(1)
예제 #15
0
 def __init__(self, host, port, username, password):
     # pylint: disable=import-error
     import fritzconnection as fc
     self._connection = fc.FritzConnection(address=host,
                                           port=port,
                                           user=username,
                                           password=password)
     self._name = "GuestWifi"
     self._state = None
     self._icon = "mdi:wifi"
     self._update_timestamp = time.time()
예제 #16
0
 def fritz_init(self):
     """ Initialize the connection to the FRITZ!Box """
     try:
         self._fc = fritzconnection.FritzConnection(
             address=self._fritz_address,
             port=self._fritz_port,
             user=self._fritz_user,
             password=self._fritz_password)
     except IOError:
         collectd.error("fritzcollectd: Failed to connect to %s" %
                        self._fritz_address)
예제 #17
0
 def __init__(self,
              fc=None,
              address=fritzconnection.FRITZ_IP_ADDRESS,
              port=fritzconnection.FRITZ_TCP_PORT):
     super(FritzStatus, self).__init__()
     if fc is None:
         fc = fritzconnection.FritzConnection(address=address, port=port)
     self.fc = fc
     self.last_bytes_sent = self.bytes_sent
     self.last_bytes_received = self.bytes_received
     self.last_traffic_call = time.time()
예제 #18
0
    def __init__(self, hass, config):
        """Initialize the connection."""
        host = config[DOMAIN].get(CONF_HOST)
        port = config[DOMAIN].get(CONF_PORT)
        username = config[DOMAIN].get(CONF_USERNAME)
        password = config[DOMAIN].get(CONF_PASSWORD)

        self._hass = hass
        self._connection = fc.FritzConnection(address=host,
                                              port=port,
                                              user=username,
                                              password=password)
예제 #19
0
    def connect(self, host, user, passwd):

        self._session = fritzconnection.FritzConnection(address=host,
                                                        port=49000,
                                                        user=user,
                                                        password=passwd)
        #  print(self._session.call_action('WANCommonInterfaceConfig', 'GetTotalBytesSent')['NewTotalBytesSent'])
        if not self._session.modelname:
            self._log.error('Cannot connect to Fritzbox')
            return False
        self._log.info('Connect to %s' % self._session.modelname)

        return self._session.modelname
예제 #20
0
 def __init__(self,
              fritz_connection=None,
              address=fritzconnection.FRITZ_IP_ADDRESS,
              port=fritzconnection.FRITZ_TCP_PORT,
              user=fritzconnection.FRITZ_USERNAME,
              password=''):
     """Initialize a FritzCallforwarding instance."""
     super(FritzCallforwarding, self).__init__()
     if fritz_connection is None:
         fritz_connection = fritzconnection.FritzConnection(
             address, port, user, password)
     self.fritz_connection = fritz_connection
     self.service = 1
예제 #21
0
파일: fritz.py 프로젝트: kunte0/fritzKolla
def main(password=PASSWORD):
    """
    Small python script to talk to your fritzbox
    """
    global c
    print('[+] Connecting to "{}" ... '.format(ADDRESS))
    c = fc.FritzConnection(address=ADDRESS, password=password)

    # check connection by getting DeviceInfo
    try:
        print('[+] Connected to ', c.call_action('DeviceInfo:1', 'GetInfo')['NewModelName'])
    except Exception as e:
        print('[-] Could not connect!')
        print(e)
        exit(1)
예제 #22
0
 def __init__(self,
              fc=None,
              address=None,
              port=None,
              user=None,
              password=None):
     super(FritzStatus, self).__init__()
     if fc is None:
         fc = fritzconnection.FritzConnection(
             address=address,
             port=port,
             user=user,
             password=password,
         )
     self.fc = fc
     self.last_bytes_sent = self.bytes_sent
     self.last_bytes_received = self.bytes_received
     self.last_traffic_call = time.time()
예제 #23
0
    def getPhoneList(self):
        FRITZ_IP = self.config.get('main', 'FRITZ_IP')
        FRITZ_USER = self.config.get('main', 'FRITZ_USER')
        FRITZ_PASSWORD = self.config.get('main', 'FRITZ_PASSWORD')

        result = "Master, versuche die Anrufe zu ermitteln.."
        telitem = [
            'Kein Call', 'Kein Call', 'Kein Call', 'Kein Call', 'Kein Call'
        ]

        f = fc.FritzConnection(address=FRITZ_IP,
                               user=FRITZ_USER,
                               password=FRITZ_PASSWORD)
        fritz = f.call_action('X_AVM-DE_OnTel', 'GetCallList')
        print(
            "This is the URL for the callers, including session token for now: "
            + fritz["NewCallListURL"])
        xmlhandle = urllib.request.urlopen(fritz["NewCallListURL"])
        xmlresult = xmlhandle.read()
        xmlhandle.close()
        root = ET.fromstring(xmlresult)
        result = "Master, hier die verpassten Anrufe (letzte 5):\n"
        thisCall = ""
        maxResults = 4
        countedresults = 0
        for callerID in root.iter('Call'):
            if callerID.find("Type").text == '2':
                callDate = callerID.find("Date").text
                inPhoneBook = callerID.find("Name").text
                callerNumber = callerID.find("Caller").text
                thisCall = callDate + ":\n"
                if callerNumber is not None:
                    thisCall = thisCall + callerNumber
                if inPhoneBook is not None:
                    thisCall = thisCall + " (" + inPhoneBook + ")"
                thisCall = thisCall + "\n"
                telitem[countedresults] = thisCall
                result = result + thisCall
                countedresults = countedresults + 1
                # print countedresults
            if countedresults > maxResults:
                # print "break now"
                break
        return {'reply': result, 'tellist': telitem}
예제 #24
0
파일: exporter.py 프로젝트: motlib/pfbex
    def __init__(self, settings, metrics):
        self.request_tm = Summary(
            'pfbex_tr64_requests',
            'Time and count for each TR-64 request to the FritzBox')

        self.conn = fc.FritzConnection(address=settings.FRITZ_HOST,
                                       user=settings.FRITZ_USER,
                                       password=settings.FRITZ_PASS)

        self._settings = settings
        self._cfg = metrics

        for item in self._cfg.values():
            item['fails'] = 0

        self._serial = 'n/a'

        self._data = {}
        self._last_clear_time = datetime.now()
예제 #25
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Set up the FRITZ!Box status sensors."""
    # pylint: disable=import-error
    import fritzconnection as fconn
    from fritzconnection.fritzconnection import FritzConnectionException

    host = config.get(CONF_HOST)
    username = config.get(CONF_USERNAME)
    password = config.get(CONF_PASSWORD)
    fc = fconn.FritzConnection(address=host, user=username, password=password)
    try:
        fstatus = fconn.FritzStatus(fc)
    except (ValueError, TypeError, FritzConnectionException):
        fstatus = None

    if fstatus is None:
        _LOGGER.error("Failed to establish connection to FRITZ!Box: %s", host)
        return 1
    else:
        _LOGGER.info("Successfully connected to FRITZ!Box")

    add_devices([FritzboxStateSensor(fc)], True)
예제 #26
0
def process_isp_logs(isp_address: str, isp_uname: str, isp_pword: str) -> list:
    """
    Function to join together multiple operations
    related to the Fritz ISP Router portion of the
    script.

    Args:
        isp_address (str): hostname / IP Address of the target FritzBox device
        isp_uname (str): Username to log in to the device
        isp_pword (str): Password to log in to the device

    Raises:
        N/A

    Returns:
        new_entries (list): List of LogEntry objects from the device
        which are not yet present in the local logfile.
        Can be used for further processing with a notifier.

    """
    # Create a logs directory to save the results into.
    log_dir = os.path.join(dirname, "..", "logs")
    output_dir = create_log_dir(log_dir=log_dir)
    log_file = f"{output_dir}/{isp_address}.log"
    # Initialise connection to Fritz ISP Router
    conn = fritzconnection.FritzConnection(address=isp_address,
                                           user=isp_uname,
                                           password=isp_pword)
    # Read log entries from the local logfile
    file_entries = load_list_from_logfile(filepath=log_file)
    device_entries = get_list_from_device(conn=conn)
    # get the log entries which are present on the device
    # but not yet written to the local logfile
    new_entries = get_list_of_new_entries(file_entries=file_entries,
                                          device_entries=device_entries)
    # Append only the log entries which are not yet present to the local logfile
    append_list_to_logfile(log_entries=new_entries, filepath=log_file)
    # return the new log entries for the notifiers of choice
    return new_entries
def init_fritzconnection():
    global fc

    fc = fritzconnection.FritzConnection(
        address=os.getenv("FB_ADDRESS"), password=os.getenv("FB_PASSWORD"))
예제 #28
0
def main():
    signal.signal(signal.SIGTERM, shutdown)
    signal.signal(signal.SIGINT, shutdown)

    # parse command line arguments
    args = parse_args()

    # set logging
    log_level = logging.DEBUG if args.debug == True else default_loglevel
    logging.basicConfig(level=log_level, format="%(levelname)s: %(message)s")

    # check if config file exists
    if not os.path.isfile(args.config_file):
        logging.error("config file \"%s\" not found" % args.config_file)
        exit(1)

    # read config from ini file
    config = read_config(args.config_file)

    logging.info("Done parsing config file")

    # set up influxdb handler
    influxdb_client = influxdb.InfluxDBClient(
        config.get('influxdb', 'host'),
        config.getint('influxdb', 'port'),
        config.get('influxdb', 'username'),
        config.get('influxdb', 'password'),
        config.get('influxdb', 'database'),
    )

    # check influx db status
    check_db_status(influxdb_client, config.get('influxdb', 'database'))

    logging.info("Connection to InfluxDB established and database present")

    # create unauthenticated FB client handler
    fritz_client_unauth = fritzconnection.FritzConnection(
        address=config.get('fritzbox', 'host'),
        port=config.get('fritzbox', 'port'),
    )

    # test connection
    if fritz_client_unauth.modelname is None:
        logging.error("Failed to connect to %s" % config.get('fritzbox', 'host'))
        exit(1)

    # create authenticated FB client handler
    fritz_client_auth = fritzconnection.FritzConnection(
        address=config.get('fritzbox', 'host'),
        port=config.get('fritzbox', 'port'),
        user=config.get('fritzbox', 'username'),
        password=config.get('fritzbox', 'password')
    )

    # test connection
    if fritz_client_auth.modelname is None:
        logging.error("Failed to connect to %s" % config.get('fritzbox', 'host'))
        exit(1)

    logging.info("Successfully connected to FritzBox")

    # read services from config file
    unauth_services = get_services(config, "service")
    auth_services = get_services(config, "auth_service")

    while running:
        points = query_points(fritz_client_unauth, unauth_services)
        points.update(query_points(fritz_client_auth, auth_services))
        data = {
            "measurement": config.get('influxdb', 'measurement_name'),
            "time": datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ'),
            "fields": points
        }
        try:
            logging.debug("writing data to InfluxDB")
            influxdb_client.write_points([data], time_precision="ms")
        except Exception:
            logging.error("Failed to write to InfluxDB %s" % config.get('influxdb', 'host'))

        # just sleep for 10 seconds
        time.sleep(10)
예제 #29
0
 def __init__(self):
     self.conn = fc.FritzConnection(password='******')
 def __init__(self, address, port, user, password):
     super(FritzAccess, self).__init__()
     self.fc = fritzconnection.FritzConnection(address, port, user,
                                               password)