示例#1
0
文件: main.py 项目: twfce/fritz2mqtt
def getFritzBoxReport(ip, password):
    print("[~] Connecting to Fritz.Box ({ip})".format(ip=ip))
    fritzStatus = FritzStatus(address=fritzIP, password=fritzPassword)
    print("[~] Requesting status information".format(ip=ip))
    statusReport = {
        "timestamp": str(datetime.now()),
        "external_ip": fritzStatus.external_ip,
        "external_ipv6": fritzStatus.external_ipv6,
        "bytes_received": fritzStatus.bytes_received,
        "bytes_sent": fritzStatus.bytes_sent,
        "is_connected": fritzStatus.is_connected,
        "is_linked": fritzStatus.is_linked,
        "bytes": fritzStatus.bytes_received,
        "max_byte_rate": {
            "up": fritzStatus.max_byte_rate[0],
            "down": fritzStatus.max_byte_rate[1]
        },
        "max_linked_bit_rate": {
            "up": fritzStatus.max_linked_bit_rate[0],
            "down": fritzStatus.max_linked_bit_rate[1]
        },
        "transmission_rate": {
            "up": fritzStatus.transmission_rate[0],
            "down": fritzStatus.transmission_rate[1]
        },
        "uptime": fritzStatus.uptime
    }
    if statusReport:
        print("{color}[+] Successfully requested status information{reset}".
              format(color=fg(2), reset=attr(0)))
    return statusReport
示例#2
0
    def setup(self) -> None:
        """Set up FritzboxTools class."""
        self.connection = FritzConnection(
            address=self.host,
            port=self.port,
            user=self.username,
            password=self.password,
            timeout=60.0,
            pool_maxsize=30,
        )

        if not self.connection:
            _LOGGER.error("Unable to establish a connection with %s",
                          self.host)
            return

        self.fritz_status = FritzStatus(fc=self.connection)
        info = self.connection.call_action("DeviceInfo:1", "GetInfo")
        if not self._unique_id:
            self._unique_id = info["NewSerialNumber"]

        self._model = info.get("NewModelName")
        self._current_firmware = info.get("NewSoftwareVersion")

        self._update_available, self._latest_firmware = self._update_device_info(
        )
示例#3
0
def print_config():
    try:
        conn = FritzStatus(address=hostname,
                           password=os.environ['fritzbox_password'])
    except Exception as e:
        print(e)
        sys.exit("Couldn't get WAN traffic")

    max_traffic = conn.max_bit_rate

    print("host_name %s" % hostname)
    print("graph_title AVM Fritz!Box WAN traffic (send)")
    print("graph_args --base 1000")
    print("graph_vlabel bit up per ${graph_period}")
    print("graph_category network")
    print("graph_order up maxup")
    print("up.label bps")
    print("up.type GAUGE")
    print("up.draw AREA")
    print("up.min 0")
    print("up.max %d" % max_traffic[0])
    print("up.warning %.0f" % (max_traffic[0] * 0.6))
    print("up.critical %.0f" % (max_traffic[0] * 0.8))
    print("up.info Traffic of the WAN interface.")
    if not os.environ.get('traffic_remove_max') or "false" in os.environ.get(
            'traffic_remove_max'):
        print("maxup.label MAX")
        print("maxup.type GAUGE")
        print("maxup.draw LINE1")
        print("maxup.info Maximum up speed of the WAN interface.")
    if os.environ.get('host_name'):
        print("host_name " + os.environ['host_name'])
示例#4
0
def cli(address, uptime, measurement):

    # fc = FritzStatus(address=address, password=password)
    fc = FritzStatus(address=address)

    if not fc.is_connected or not fc.is_linked:
        print(f'is_connected={fc.is_connected}, ' f'is_linked={fc.is_linked}')
        sys.exit(SENSU_EXIT_CRITICAL)

    if not fc.bytes_received or not fc.bytes_sent:
        print(f'bytes_received={fc.bytes_received}, '
              f'bytes_sent={fc.bytes_sent}')
        sys.exit(SENSU_EXIT_CRITICAL)

    fields = {
        'received': fc.bytes_received,
        'sent': fc.bytes_sent,
        'uptime': fc.uptime
    }

    tags = {
        'hostname': address,
        'ipv4': fc.external_ip,
        'ipv6': fc.external_ipv6
    }

    def _key_values(d):
        return ['%s=%s' % (k, v) for k, v in d.items()]

    print('{measurement},{tags} {fields}'.format(
        measurement=measurement,
        tags=','.join(_key_values(tags)),
        fields=','.join(_key_values(fields))))

    sys.exit(SENSU_EXIT_OK if fc.uptime > uptime else SENSU_EXIT_WARNING)
示例#5
0
 def __init__(self):
     config = FritzboxConfig()
     try:
         self.__connection = FritzStatus(address=config.server,
                                         password=config.password,
                                         use_tls=config.useTls)
     except Exception as e:
         sys.exit("Couldn't get WAN traffic: " + str(e))
示例#6
0
def getFritzStatus():
    fs = FritzStatus(fc)
    print("*************** Status FritzBox! ********************\n")
    print("FritzBox Model: %s" % (fs.modelname))
    print("FritzBox is linked: ", fs.is_linked)
    print("FritzBox is connected:", fs.is_connected)
    print("FritzBox uptime:", fs.str_uptime)
    print("FritzBox external IP4: %s\n" % (fs.external_ip))
def print_values():
    try:
        conn = FritzStatus(address=hostname,
                           password=os.environ['fritzbox_password'])
    except Exception:
        sys.exit("Couldn't get connection uptime")

    uptime = conn.uptime
    print('uptime.value %.2f' % (int(uptime) / 3600.0))
def get_info():
    status = FritzStatus(fc)
    device_info = fc.call_action("DeviceInfo1", "GetInfo")
    description = device_info.get("NewDescription")
    software_version = device_info.get("NewSoftwareVersion")
    serial_number = device_info.get("NewSerialNumber")
    uptime = device_info.get("NewUpTime")
    info_metric.info({"model": status.modelname, "software_version": software_version,
                      "device_description": description, "serial_number": serial_number})
    uptime_metric.set(uptime)
示例#9
0
    def connect(self):
        Domoticz.Debug("Try to get FritzStatus Connection")

        # all params ae optional an can handle it, if they are empty
        # so for pw free status mode, this works as well
        self.fcStatus = FritzStatus(address=self.host,
                                    user=self.user,
                                    password=self.password)
        Domoticz.Debug("status: {}".format(self.fcStatus))
        return self.fcStatus
示例#10
0
    def ip(self) -> IPv4Address:
        try:
            fc = FritzStatus(address=self.fritzbox_ip)
            ip = IPv4Address(fc.external_ip)
        except AddressValueError:
            logging.error(
                f"unable to get external ip from FRITZ!Box {self.fritzbox_ip}")
            return None
        except ConnectionError:
            logging.error(f"unable to connect to FRITZ!Box {self.fritzbox_ip}")
            return None

        logging.debug(f"found external ip to be {ip}")
        return ip
示例#11
0
    def __init__(
        self,
        password,
        username = DEFAULT_USERNAME,
        host = DEFAULT_HOST,
        port=DEFAULT_PORT,
        profile_on = DEFAULT_PROFILE_ON,
        profile_off = DEFAULT_PROFILE_OFF,
        device_list = DEFAULT_DEVICES,
        use_port = DEFAULT_USE_PORT,
        use_deflections = DEFAULT_USE_DEFLECTIONS,
        use_wifi = DEFAULT_USE_WIFI,
        use_devices = DEFAULT_USE_DEVICES,
    ):
        # pylint: disable=import-error
        from fritzconnection import FritzConnection
        from fritzconnection.lib.fritzstatus import FritzStatus
        from fritz_switch_profiles import FritzProfileSwitch

        # general timeout for all requests to the router. Some calls need quite some time.
        self.connection = FritzConnection(
            address=host, port=port, user=username, password=password, timeout=30.0
        )

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

        self.fritzstatus = 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

        self.use_wifi = use_wifi
        self.use_port = use_port
        self.use_deflections = use_deflections
        self.use_devices = use_devices

        self._unique_id = self.connection.call_action("DeviceInfo:1", "GetInfo")[
            "NewSerialNumber"
        ]
        self._device_info = self._fetch_device_info()
示例#12
0
 def _poll_loop(self):
     self._current_data = FritzBoxData()
     last_hosts: Optional[datetime] = None
     while self._running:
         try:
             self._current_data.status = FritzStatus(address=self._address, password=self._password)
             if not last_hosts or (datetime.now() - last_hosts) / timedelta(seconds=10) >= 1:
                 self.current_data.hosts = FritzHosts(address=self._address, password=self._password)
                 self.current_data.wlan = FritzWLAN(address=self._address, password=self._password)
                 last_hosts = datetime.now()
         except IOError as e:
             log.warning(f"Failed to get FritzBox data: {e}")
         self._notify_listeners()
         self._queue.get()
示例#13
0
def setup_platform(hass, config, add_entities, discovery_info=None):
    """Set up the FRITZ!Box monitor sensors."""
    name = config.get(CONF_NAME)
    host = config.get(CONF_HOST)

    try:
        fstatus = FritzStatus(address=host)
    except (ValueError, TypeError, FritzConnectionException):
        fstatus = None

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

    add_entities([FritzboxMonitorSensor(name, fstatus)], True)
示例#14
0
    def setup(self):
        """Set up FritzboxTools class."""
        self.connection = FritzConnection(
            address=self.host,
            port=self.port,
            user=self.username,
            password=self.password,
            timeout=60.0,
        )

        self.fritzstatus = FritzStatus(fc=self.connection)
        if self._unique_id is None:
            self._unique_id = self.connection.call_action(
                "DeviceInfo:1", "GetInfo")["NewSerialNumber"]

        self._device_info = self._fetch_device_info()
示例#15
0
文件: common.py 项目: liann1991/core
    def setup(self) -> None:
        """Set up FritzboxTools class."""
        self.connection = FritzConnection(
            address=self.host,
            port=self.port,
            user=self.username,
            password=self.password,
            timeout=60.0,
            pool_maxsize=30,
        )

        if not self.connection:
            _LOGGER.error("Unable to establish a connection with %s",
                          self.host)
            return

        _LOGGER.debug(
            "detected services on %s %s",
            self.host,
            list(self.connection.services.keys()),
        )

        self.fritz_hosts = FritzHosts(fc=self.connection)
        self.fritz_status = FritzStatus(fc=self.connection)
        info = self.connection.call_action("DeviceInfo:1", "GetInfo")

        _LOGGER.debug(
            "gathered device info of %s %s",
            self.host,
            {
                **info,
                "NewDeviceLog": "***omitted***",
                "NewSerialNumber": "***omitted***",
            },
        )

        if not self._unique_id:
            self._unique_id = info["NewSerialNumber"]

        self._model = info.get("NewModelName")
        self._current_firmware = info.get("NewSoftwareVersion")

        self._update_available, self._latest_firmware = self._update_device_info(
        )
        self.device_is_router = "WANIPConn1" in self.connection.services
示例#16
0
    def setup(self):
        """Set up FritzboxTools class."""
        self.connection = FritzConnection(
            address=self.host,
            port=self.port,
            user=self.username,
            password=self.password,
            timeout=60.0,
        )

        self.fritz_status = FritzStatus(fc=self.connection)
        info = self.connection.call_action("DeviceInfo:1", "GetInfo")
        if self._unique_id is None:
            self._unique_id = info["NewSerialNumber"]

        self.model = info.get("NewModelName")
        self.sw_version = info.get("NewSoftwareVersion")
        self.mac = self.unique_id
def print_values():
    try:
        conn = FritzStatus(address=hostname, password=os.environ['fritzbox_password'])
    except Exception as e:
        print(e)
        sys.exit("Couldn't get WAN traffic")

    traffic =  conn.transmission_rate
    up = traffic[0]*8
    down = traffic[1]*8
    print('down.value %d' % down)

    print('up.value %d' % up)

    if not os.environ.get('traffic_remove_max') or "false" in os.environ.get('traffic_remove_max'):
        max_traffic = conn.max_bit_rate
        print('maxdown.value %d' % max_traffic[1])

        print('maxup.value %d' % max_traffic[0])
示例#18
0
 def __init__(self, ff_config):
     self.fc = FritzConnection(address=ff_config["fb_address"],
                               user=ff_config["fb_user"],
                               password=ff_config["fb_pass"])
     self.fs = FritzStatus(self.fc)
     self.fh = FritzHomeAutomation(self.fc)
     self.ic = []
     for iconfig in ff_config["influxdb_connections"]:
         if is_influx2_db(iconfig):
             self.ic.append(
                 InfluxDBClient(url=iconfig["url"], token=iconfig["token"]))
         else:
             self.ic.append(
                 influxdb.InfluxDBClient(host=iconfig["address"],
                                         port=iconfig["port"],
                                         username=iconfig["user"],
                                         password=iconfig["pass"],
                                         database=iconfig["database"]))
     self.config = ff_config
示例#19
0
def main(addresses: tuple):
    logging.basicConfig(
        level=config.loglevel,
        format=
        "%(asctime)s %(levelname)s %(processName)s/%(module)s[%(process)d]: %(message)s "
        "[%(pathname)s:%(lineno)d]")

    fritzbox = FritzStatus(address=config.address,
                           user=config.user,
                           password=config.password,
                           use_tls=config.tls,
                           timeout=config.timeout)

    exposed_host_ipv6: str = ipaddress.IPv6Address(
        fritzbox.ipv6_prefix[:-1] + config.ipv6_node_id).exploded

    logger.debug("Fritzbox API: Connection established, address={}".format(
        config.address))

    if fritzbox.is_connected:
        if addresses[0] != fritzbox.external_ip or addresses[
                1] != exposed_host_ipv6:
            netcup = Netcup(config.nc_customer_number, config.nc_api_key,
                            config.nc_api_pw)

            netcup.login()
            dnsrecords = netcup.getRecords(config.domain)
            updates = list()

            for a_record in config.host.split(','):
                queue_update_for_record(dnsrecords, fritzbox,
                                        exposed_host_ipv6, a_record, updates)

            netcup.updateRecords(config.domain, updates)
            netcup.logout()
        else:
            logger.debug("No IP address change detected")
    else:
        logger.error("Connection to {} failed".format(config.address))

    return fritzbox.external_ip, exposed_host_ipv6
示例#20
0
    def setup(self) -> None:
        """Set up FritzboxTools class."""
        self.connection = FritzConnection(
            address=self.host,
            port=self.port,
            user=self.username,
            password=self.password,
            timeout=60.0,
        )

        self.fritz_status = FritzStatus(fc=self.connection)
        info = self.connection.call_action("DeviceInfo:1", "GetInfo")
        if not self._unique_id:
            self._unique_id = info["NewSerialNumber"]

        self._model = info.get("NewModelName")
        self._sw_version = info.get("NewSoftwareVersion")

        self.fritz_profiles = {
            profile: FritzProfileSwitch("http://" + self.host, self.username,
                                        self.password, profile)
            for profile in get_all_profiles(self.host, self.username,
                                            self.password)
        }
with open("conf", "r") as config:
    key = config.readline().split(":", 1)[-1].strip()
    allowed_users = [
        int(x) for x in config.readline().split(':', 1)[-1].strip().split(',')
        if len(x) > 0
    ]
    router_ip = config.readline().split(':', 1)[-1].strip()
    router_pw = config.readline().split(':', 1)[-1].strip()
    db_vals = config.readline().split(':', 1)[-1].strip()
    user, user_pw, location, port, database = db_vals.split(',')
    port = int(port)

router_connection = FritzConnection(address=router_ip, password=router_pw)
router_wlan = FritzWLAN(router_connection)
router_host = FritzHosts(router_connection)
router_status = FritzStatus(router_connection)

router_model = router_status.modelname

metadata = MetaData()
db_engine = create_engine(
    f'mysql+pymysql://{user}:{user_pw}@{location}:{port}/{database}')
metadata.reflect(db_engine, only=['stats'])
Base = automap_base(metadata=metadata)
Base.prepare()
db_statistics_class = Base.classes.stats
Session = sessionmaker(bind=db_engine)
db_session = Session()


# general functions
示例#22
0
    def __init__(
        self,
        password,
        username=DEFAULT_USERNAME,
        host=DEFAULT_HOST,
        port=DEFAULT_PORT,
        profile_list=DEFAULT_PROFILES,
        use_port=DEFAULT_USE_PORT,
        use_deflections=DEFAULT_USE_DEFLECTIONS,
        use_wifi=DEFAULT_USE_WIFI,
        use_profiles=DEFAULT_USE_PROFILES,
    ):
        # pylint: disable=import-error
        from fritzconnection import FritzConnection
        from fritzconnection.lib.fritzstatus import FritzStatus
        from fritzprofiles import FritzProfileSwitch
        from fritzconnection.core.exceptions import FritzConnectionException

        # general timeout for all requests to the router. Some calls need quite some time.

        try:
            self.connection = FritzConnection(address=host,
                                              port=port,
                                              user=username,
                                              password=password,
                                              timeout=60.0)
            if profile_list != DEFAULT_PROFILES:
                self.profile_switch = {
                    profile: FritzProfileSwitch("http://" + host, username,
                                                password, profile)
                    for profile in profile_list
                }
            else:
                self.profile_switch = {}

            self.fritzstatus = FritzStatus(fc=self.connection)
            self._unique_id = self.connection.call_action(
                "DeviceInfo:1", "GetInfo")["NewSerialNumber"]
            self._device_info = self._fetch_device_info()
            self.success = True
            self.error = False
        except FritzConnectionException:
            self.success = False
            self.error = "connection_error"
        except PermissionError:
            self.success = False
            self.error = "connection_error_profiles"
        except AttributeError:
            self.success = False
            self.error = "profile_not_found"

        self.ha_ip = get_local_ip()
        self.profile_list = profile_list

        self.username = username
        self.password = password
        self.port = port
        self.host = host

        self.use_wifi = use_wifi
        self.use_port = use_port
        self.use_deflections = use_deflections
        self.use_profiles = use_profiles
示例#23
0
#!/usr/local/opt/[email protected]/bin/python3

import time

from fritzconnection.lib.fritzstatus import FritzStatus

fc = FritzStatus(address="192.168.178.1")
while True:
    print(
        f"Linked: {fc.is_connected} -- Connected: {fc.is_linked} -- max bit rate: {fc.str_max_bit_rate} -- trans rate: {fc.str_transmission_rate}"
    )
    time.sleep(2)
示例#24
0
    print("We need to be root for changing ip routes. Exiting..")
    sys.exit()

FNULL = open(os.devnull, 'w')

PING_TEST_HOST = os.environ.get('FO_PING_HOST', '8.8.8.8')
FRITZBOX_GATEWAY = os.environ.get('FRITZBOX_GATEWAY', '192.168.178.1')
FAILOVER_GATEWAY = os.environ.get('FAILOVER_GATEWAY', '192.168.178.10')
INTERFACE = os.environ.get('FO_INTERFACE', 'enp3s0')
FRITZBOX_PASSWORD = os.environ.get('FRITZBOX_PASSWORD',
                                   getpass(prompt='FritzBox Password: '******'ip', 'route', 'change', 'default', 'via', gateway, 'dev', INTERFACE])
    subprocess.call(['ip', 'route', 'flush', 'cache'])
    print("changed gateway to: {}".format(gateway))


def testPing():
    return subprocess.run(
        ['ping', '-4', '-c', '1', '-w', '3', '-q', PING_TEST_HOST],
        stdout=FNULL).returncode == 0