示例#1
0
from fritzconnection import FritzConnection
import telepot
import re

connection = FritzConnection(password='******')
ip = connection.call_action('WANPPPConnection', 'GetInfo')['NewExternalIPAddress']

match = re.search('^100\.', ip)

if match:
    bot = telepot.Bot('TELEGRAM_BOT_TOKEN');
    bot.sendMessage('@TELEGRAM_GROUP', 'I\'ve got IP: %s and I don\'t like it.' % ip)
    connection.reconnect()
示例#2
0
class FritzBoxTools(object):
    """
    Attention: The initialization of the class performs sync I/O. If you're calling this from within Home Assistant,
    wrap it in await self.hass.async_add_executor_job(lambda: FritzBoxTools(...))
    """
    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()

    async def async_update_profiles(self, hass):
        if time.time() > self.profile_last_updated + 5:
            # do not update profiles too often (takes too long...)!
            await hass.async_add_executor_job(self.profile_switch.fetch_profiles)
            await hass.async_add_executor_job(self.profile_switch.fetch_devices)
            await hass.async_add_executor_job(self.profile_switch.fetch_device_profiles)
            self.profile_last_updated = time.time()

    def service_reconnect_fritzbox(self, call) -> None:
        _LOGGER.info("Reconnecting the fritzbox.")
        self.connection.reconnect()

    def is_ok(self):
        # TODO for future: do more of the async_setup_entry checks right here

        from fritzconnection.core.exceptions import FritzConnectionException

        try:
            _ = self.connection.call_action(
                "Layer3Forwarding:1", "GetDefaultConnectionService"
            )["NewDefaultConnectionService"]
            return True, ""
        except FritzConnectionException:
            return False, "connection_error"

    @property
    def unique_id(self):
        return self._unique_id

    @property
    def device_info(self):
        return self._device_info

    def _fetch_device_info(self):
        info = self.connection.call_action("DeviceInfo:1", "GetInfo")
        return {
            "identifiers": {
                # Serial numbers are unique identifiers within a specific domain
                (DOMAIN, self.unique_id)
            },
            "name": info.get("NewProductClass"),
            "manufacturer": "AVM",
            "model": info.get("NewModelName"),
            "sw_version": info.get("NewSoftwareVersion"),
        }
示例#3
0
                     tgbot.send_message(chat_id=tg_chatid,
                                        text=msg_tg + "\n```csv\n" +
                                        version_str + "\n```",
                                        parse_mode=ParseMode.MARKDOWN)
                     submitVersion(version, uid)
                     sleep(sleep_after_client_new_version)
                 except query.TS3QueryError as err:
                     logger.error(err.args[0])
                     continue
                 except:
                     logger.error(format_exc())
                     continue
             logger.info("Successfully sniffed {}/{} clients".format(
                 success_clients, len(clientlist)))
             success += 1
     except query.TS3TransportError as err:
         logger.warning(
             "Connection blocked by firewall, changing IP and waiting 30s before next run..."
         )
         neednewip = True
         continue
     except:
         logger.error(format_exc())
         continue
 logger.info("Successfully sniffed {}/{} servers".format(
     success, len(servers)))
 if neednewip:
     fritzbox.reconnect()
     sleep(sleep_ipchange)
 else:
     sleep(sleep_after_run)
示例#4
0
class FritzBoxTools(object):
    """
    Attention: The initialization of the class performs sync I/O. If you're calling this from within Home Assistant,
    wrap it in await self.hass.async_add_executor_job(lambda: FritzBoxTools(...))
    """
    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

    def service_reconnect_fritzbox(self) -> None:
        _LOGGER.info("Reconnecting the fritzbox.")
        self.connection.reconnect()

    def service_reboot_fritzbox(self) -> None:
        _LOGGER.info("Rebooting the fritzbox.")
        self.connection.call_action("DeviceConfig1", "Reboot")

    def is_ok(self):
        return self.success, self.error

    @property
    def unique_id(self):
        return self._unique_id

    @property
    def fritzbox_model(self):
        return self._device_info["model"].replace("FRITZ!Box ", "")

    @property
    def device_info(self):
        return self._device_info

    def _fetch_device_info(self):
        info = self.connection.call_action("DeviceInfo:1", "GetInfo")
        return {
            "identifiers": {
                # Serial numbers are unique identifiers within a specific domain
                (DOMAIN, self.unique_id)
            },
            "name": info.get("NewModelName"),
            "manufacturer": "AVM",
            "model": info.get("NewModelName"),
            "sw_version": info.get("NewSoftwareVersion"),
        }