コード例 #1
0
    def __init__(self, hass, device_info):
        """Initialize a generic camera."""
        super().__init__()
        self.hass = hass
        self._authentication = device_info.get(CONF_AUTHENTICATION)
        self._name = device_info.get(CONF_NAME)
        self._still_image_url = device_info[CONF_STILL_IMAGE_URL]
        self._stream_source = device_info.get(CONF_STREAM_SOURCE)
        self._still_image_url.hass = hass
        if self._stream_source is not None:
            self._stream_source.hass = hass
        self._limit_refetch = device_info[CONF_LIMIT_REFETCH_TO_URL_CHANGE]
        self._frame_interval = 1 / device_info[CONF_FRAMERATE]
        self._supported_features = SUPPORT_STREAM if self._stream_source else 0
        self.content_type = device_info[CONF_CONTENT_TYPE]
        self.verify_ssl = device_info[CONF_VERIFY_SSL]
        if device_info.get(CONF_RTSP_TRANSPORT):
            self.stream_options[FFMPEG_OPTION_MAP[
                CONF_RTSP_TRANSPORT]] = device_info[CONF_RTSP_TRANSPORT]

        username = device_info.get(CONF_USERNAME)
        password = device_info.get(CONF_PASSWORD)

        if username and password:
            if self._authentication == HTTP_DIGEST_AUTHENTICATION:
                self._auth = httpx.DigestAuth(username=username,
                                              password=password)
            else:
                self._auth = httpx.BasicAuth(username=username,
                                             password=password)
        else:
            self._auth = None

        self._last_url = None
        self._last_image = None
コード例 #2
0
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Set up Scrape from a config entry."""

    resource: str = entry.options[CONF_RESOURCE]
    method: str = "GET"
    payload: str | None = None
    headers: str | None = entry.options.get(CONF_HEADERS)
    verify_ssl: bool = entry.options[CONF_VERIFY_SSL]
    username: str | None = entry.options.get(CONF_USERNAME)
    password: str | None = entry.options.get(CONF_PASSWORD)

    auth: httpx.DigestAuth | tuple[str, str] | None = None
    if username and password:
        if entry.options.get(
                CONF_AUTHENTICATION) == HTTP_DIGEST_AUTHENTICATION:
            auth = httpx.DigestAuth(username, password)
        else:
            auth = (username, password)

    rest = RestData(hass, method, resource, auth, headers, None, payload,
                    verify_ssl)
    await rest.async_update()

    if rest.data is None:
        raise ConfigEntryNotReady

    hass.data.setdefault(DOMAIN, {})[entry.entry_id] = rest

    entry.async_on_unload(entry.add_update_listener(async_update_listener))

    hass.config_entries.async_setup_platforms(entry, PLATFORMS)

    return True
コード例 #3
0
    async def inverters_production(self):
        """Hit a different Envoy endpoint and get the production values for
         individual inverters"""
        """If a password was not given as an argument when instantiating
        the EnvoyReader object than use the last six numbers of the serial
        number as the password.  Otherwise use the password argument value."""
        if self.password == "":
            if self.serial_number_last_six == "":
                await self.get_serial_number()
                self.password = self.serial_number_last_six

        try:
            async with httpx.AsyncClient() as client:
                response = await client.get(
                    "http://{}/api/v1/production/inverters".format(self.host),
                    auth=httpx.DigestAuth(self.username, self.password))
            if response is not None and response.status_code != 401:
                response_dict = {}
                for item in response.json():
                    response_dict[item["serialNumber"]] = [
                        item["lastReportWatts"],
                        time.strftime('%Y-%m-%d %H:%M:%S',
                                      time.localtime(item["lastReportDate"]))
                    ]
                return response_dict
            else:
                response.raise_for_status()
        except httpx.HTTPError:
            return self.create_connect_errormessage()
        except (json.decoder.JSONDecodeError, KeyError, IndexError, TypeError):
            return self.create_json_errormessage()
        except h11.RemoteProtocolError:
            await response.close()
コード例 #4
0
ファイル: http.py プロジェクト: mitchmitchell/python-amcrest
    async def _async_generate_token(self) -> None:
        """Create authentation to use with requests."""
        cmd = "magicBox.cgi?action=getMachineName"
        _LOGGER.debug("%s Trying async Basic Authentication", self)
        self._async_token = httpx.BasicAuth(self._user, self._password)
        try:
            try:
                resp = (await self._async_command(cmd)).content.decode()
            except LoginError:
                _LOGGER.debug("%s Trying async Digest Authentication", self)
                self._async_token = httpx.DigestAuth(self._user,
                                                     self._password)
                resp = (await self._async_command(cmd)).content.decode()
        except CommError:
            self._async_token = None
            raise

        # check if user passed
        result = resp.lower()
        if "invalid" in result or "error" in result:
            _LOGGER.debug(
                "%s Result from camera: %s",
                self,
                resp.strip().replace("\r\n", ": "),
            )
            self._async_token = None
            raise LoginError("Invalid credentials")

        self._name = pretty(resp.strip())

        _LOGGER.debug("%s Retrieving serial number", self)
        self._serial = pretty(
            (await self._async_command("magicBox.cgi?action=getSerialNo")
             ).content.decode().strip())
コード例 #5
0
ファイル: sensor.py プロジェクト: uzbekdev1/core-2
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
    """Set up the Web scrape sensor."""
    name = config.get(CONF_NAME)
    resource = config.get(CONF_RESOURCE)
    method = "GET"
    payload = None
    headers = config.get(CONF_HEADERS)
    verify_ssl = config.get(CONF_VERIFY_SSL)
    select = config.get(CONF_SELECT)
    attr = config.get(CONF_ATTR)
    index = config.get(CONF_INDEX)
    unit = config.get(CONF_UNIT_OF_MEASUREMENT)
    username = config.get(CONF_USERNAME)
    password = config.get(CONF_PASSWORD)
    value_template = config.get(CONF_VALUE_TEMPLATE)
    if value_template is not None:
        value_template.hass = hass

    if username and password:
        if config.get(CONF_AUTHENTICATION) == HTTP_DIGEST_AUTHENTICATION:
            auth = httpx.DigestAuth(username, password)
        else:
            auth = (username, password)
    else:
        auth = None
    rest = RestData(hass, method, resource, auth, headers, None, payload, verify_ssl)
    await rest.async_update()

    if rest.data is None:
        raise PlatformNotReady

    async_add_entities(
        [ScrapeSensor(rest, name, select, attr, index, value_template, unit)], True
    )
コード例 #6
0
ファイル: __init__.py プロジェクト: rikroe/core
def create_rest_data_from_config(hass, config):
    """Create RestData from config."""
    resource = config.get(CONF_RESOURCE)
    resource_template = config.get(CONF_RESOURCE_TEMPLATE)
    method = config.get(CONF_METHOD)
    payload = config.get(CONF_PAYLOAD)
    verify_ssl = config.get(CONF_VERIFY_SSL)
    username = config.get(CONF_USERNAME)
    password = config.get(CONF_PASSWORD)
    headers = config.get(CONF_HEADERS)
    params = config.get(CONF_PARAMS)
    timeout = config.get(CONF_TIMEOUT)

    if resource_template is not None:
        resource_template.hass = hass
        resource = resource_template.async_render(parse_result=False)

    template.attach(hass, headers)
    template.attach(hass, params)

    if username and password:
        if config.get(CONF_AUTHENTICATION) == HTTP_DIGEST_AUTHENTICATION:
            auth = httpx.DigestAuth(username, password)
        else:
            auth = (username, password)
    else:
        auth = None

    return RestData(hass, method, resource, auth, headers, params, payload,
                    verify_ssl, timeout)
コード例 #7
0
ファイル: httpbin_async_test.py プロジェクト: bkryza/decorest
async def test_digest_auth(client):
    """
    """
    auth = httpx.DigestAuth('user', 'password')

    res = await client.digest_auth('auth', 'user', 'password', auth=auth)

    assert res['authenticated'] is True
コード例 #8
0
async def async_setup_platform(hass,
                               config,
                               async_add_entities,
                               discovery_info=None):
    """Set up the REST binary sensor."""

    await async_setup_reload_service(hass, DOMAIN, PLATFORMS)

    name = config.get(CONF_NAME)
    resource = config.get(CONF_RESOURCE)
    resource_template = config.get(CONF_RESOURCE_TEMPLATE)
    method = config.get(CONF_METHOD)
    payload = config.get(CONF_PAYLOAD)
    verify_ssl = config.get(CONF_VERIFY_SSL)
    timeout = config.get(CONF_TIMEOUT)
    username = config.get(CONF_USERNAME)
    password = config.get(CONF_PASSWORD)
    headers = config.get(CONF_HEADERS)
    device_class = config.get(CONF_DEVICE_CLASS)
    value_template = config.get(CONF_VALUE_TEMPLATE)
    force_update = config.get(CONF_FORCE_UPDATE)

    if resource_template is not None:
        resource_template.hass = hass
        resource = resource_template.render(parse_result=False)

    if value_template is not None:
        value_template.hass = hass

    if username and password:
        if config.get(CONF_AUTHENTICATION) == HTTP_DIGEST_AUTHENTICATION:
            auth = httpx.DigestAuth(username, password)
        else:
            auth = (username, password)
    else:
        auth = None

    rest = RestData(method, resource, auth, headers, payload, verify_ssl,
                    timeout)
    await rest.async_update()
    if rest.data is None:
        raise PlatformNotReady

    async_add_entities(
        [
            RestBinarySensor(
                hass,
                rest,
                name,
                device_class,
                value_template,
                force_update,
                resource_template,
            )
        ],
        True,
    )
コード例 #9
0
async def async_setup_platform(
    hass: HomeAssistant,
    config: ConfigType,
    async_add_entities: AddEntitiesCallback,
    discovery_info: DiscoveryInfoType | None = None,
) -> None:
    """Set up the Web scrape sensor."""
    name: str = config[CONF_NAME]
    resource: str = config[CONF_RESOURCE]
    method: str = "GET"
    payload: str | None = None
    headers: str | None = config.get(CONF_HEADERS)
    verify_ssl: bool = config[CONF_VERIFY_SSL]
    select: str | None = config.get(CONF_SELECT)
    attr: str | None = config.get(CONF_ATTR)
    index: int = config[CONF_INDEX]
    unit: str | None = config.get(CONF_UNIT_OF_MEASUREMENT)
    device_class: str | None = config.get(CONF_DEVICE_CLASS)
    state_class: str | None = config.get(CONF_STATE_CLASS)
    username: str | None = config.get(CONF_USERNAME)
    password: str | None = config.get(CONF_PASSWORD)
    value_template: Template | None = config.get(CONF_VALUE_TEMPLATE)

    if value_template is not None:
        value_template.hass = hass

    auth: httpx.DigestAuth | tuple[str, str] | None = None
    if username and password:
        if config.get(CONF_AUTHENTICATION) == HTTP_DIGEST_AUTHENTICATION:
            auth = httpx.DigestAuth(username, password)
        else:
            auth = (username, password)

    rest = RestData(hass, method, resource, auth, headers, None, payload,
                    verify_ssl)
    await rest.async_update()

    if rest.data is None:
        raise PlatformNotReady

    async_add_entities(
        [
            ScrapeSensor(
                rest,
                name,
                select,
                attr,
                index,
                value_template,
                unit,
                device_class,
                state_class,
            )
        ],
        True,
    )
コード例 #10
0
def generate_auth(device_info) -> httpx.Auth | None:
    """Generate httpx.Auth object from credentials."""
    username = device_info.get(CONF_USERNAME)
    password = device_info.get(CONF_PASSWORD)
    authentication = device_info.get(CONF_AUTHENTICATION)
    if username:
        if authentication == HTTP_DIGEST_AUTHENTICATION:
            return httpx.DigestAuth(username=username, password=password)
        return httpx.BasicAuth(username=username, password=password)
    return None
コード例 #11
0
ファイル: httpbin_test.py プロジェクト: bkryza/decorest
def test_digest_auth(client):
    """
    """
    if client._backend() == 'requests':
        auth = HTTPDigestAuth('user', 'password')
    else:
        import httpx
        auth = httpx.DigestAuth('user', 'password')

    res = client.digest_auth('auth', 'user', 'password', auth=auth)

    assert res['authenticated'] is True
コード例 #12
0
 async def getAPIv1Inverters(self):
     await self.get_serial_number()
     if response_api_v1_inverters in self.cached_response:
         raw_json = self.cached_response[response_api_v1_inverters]
     else:
         auth = httpx.DigestAuth(self.username, self.password)
         status_code, raw_json = await self.getEnvoyResponse(INVERTERS_API_URL, auth=auth)
         if status_code == 200:
             self.cached_response[response_api_v1_inverters] = raw_json
         else:
             raw_json = None
     return raw_json
コード例 #13
0
ファイル: test_auth.py プロジェクト: githubassets/httpx-1
def test_digest_auth_with_200():
    auth = httpx.DigestAuth(username="******", password="******")
    request = httpx.Request("GET", "https://www.example.com")

    # The initial request should not include an auth header.
    flow = auth.sync_auth_flow(request)
    request = next(flow)
    assert "Authorization" not in request.headers

    # If a 200 response is returned, then no other requests are made.
    response = httpx.Response(content=b"Hello, world!", status_code=200)
    with pytest.raises(StopIteration):
        flow.send(response)
コード例 #14
0
    async def _detect_auth_method(self):
        """Establish the connection with device"""
        full_url = urljoin(self.host, self.isapi_prefix + '/System/status')
        for method in [
                httpx.BasicAuth(self.login, self.password),
                httpx.DigestAuth(self.login, self.password),
        ]:
            async with httpx.AsyncClient(auth=method) as client:
                response = await client.get(full_url)
                if response.status_code == 200:
                    self._auth_method = method

        if not self._auth_method:
            response.raise_for_status()
コード例 #15
0
 def __init__(self, hostaddr: str, auth_user: str, auth_pass: str, hostport: int = 80):
     if hostaddr.endswith('/'):
         hostaddr = hostaddr.rstrip('/')
     if not hostaddr.startswith('http'):
         hostaddr = f'http://{hostaddr}'
     self.hostaddr = hostaddr
     self.hostport = hostport
     self._client = None
     if auth_user is None:
         auth_user = ''
     if auth_pass is None:
         auth_pass = ''
     self.auth = httpx.DigestAuth(auth_user, auth_pass)
     self._authenticated = False
     self._error = False
コード例 #16
0
    def auth_method(self, value):
        """Set the authentication method to use for the requests."""
        self._auth_method = value
        if len(self._auth_credentials) == 2:
            username, password = self._auth_credentials
            self._auth = None

            if self._auth_method == "basic":
                self._auth = httpx.BasicAuth(username, password)
            elif self._auth_method == "digest":
                self._auth = httpx.DigestAuth(username, password)
            elif self._auth_method == "ntlm":
                # https://github.com/ulodciv/httpx-ntlm
                from httpx_ntlm import HttpNtlmAuth
                self._auth = HttpNtlmAuth(
                    username, password)  # username in the form domain\user

            self.client.auth = self._auth
コード例 #17
0
ファイル: webskan.py プロジェクト: Rz7-h2k/WebCam-Skan
def brute_pass(dir_ip, port):
    user_web = ['admin', '']
    user_pass = [
        'admin', '', '12345', '123456', '1234567', '12345678', '123456789',
        '1234567890', '11111'
    ]
    try:
        for user in user_web:
            for password in user_pass:
                auth = httpx.DigestAuth(user, password)
                cam_get = httpx.get("http://" + dir_ip + ":" + port, auth=auth)
                if cam_get.status_code == 200:
                    print("=* http://" + user + ":" + password + "@" + dir_ip +
                          ":" + port + "/")
                    goahead_ok.append(dir_ip)
                    break

    except httpx.ConnectTimeout:
        print(dir_ip + " Error")
コード例 #18
0
ファイル: envoy_reader.py プロジェクト: onkelbeh/envoy_reader
    async def getData(self, getInverters=True):  # pylint: disable=invalid-name
        """Fetch data from the endpoint and if inverters selected default"""
        """to fetching inverter data."""

        # Check if the Secure flag is set
        if self.https_flag == "s":
            _LOGGER.debug("Checking Token value: %s", self._token)
            # Check if a token has already been retrieved
            if self._token == "":
                _LOGGER.debug("Found empty token: %s", self._token)
                await self._getEnphaseToken()
            else:
                _LOGGER.debug("Token is populated: %s", self._token)
                if self._is_enphase_token_expired(self._token):
                    _LOGGER.debug("Found Expired token - Retrieving new token")
                    await self._getEnphaseToken()

        if not self.endpoint_type:
            await self.detect_model()
        else:
            await self._update()

        if not self.get_inverters or not getInverters:
            return

        inverters_url = ENDPOINT_URL_PRODUCTION_INVERTERS.format(
            self.https_flag, self.host)
        inverters_auth = httpx.DigestAuth(self.username, self.password)

        response = await self._async_fetch_with_retry(inverters_url,
                                                      auth=inverters_auth)
        _LOGGER.debug(
            "Fetched from %s: %s: %s",
            inverters_url,
            response,
            response.text,
        )
        if response.status_code == 401:
            response.raise_for_status()
        self.endpoint_production_inverters = response
        return
コード例 #19
0
    def __init__(self, config: Configuration) -> None:
        """Store local reference to device config."""
        self.config = config
        self.auth = httpx.DigestAuth(self.config.username,
                                     self.config.password)

        self.api_discovery: Optional[ApiDiscovery] = None
        self.applications: Optional[Applications] = None
        self.basic_device_info: Optional[BasicDeviceInfo] = None
        self.event_instances: Optional[EventInstances] = None
        self.fence_guard: Optional[FenceGuard] = None
        self.light_control: Optional[LightControl] = None
        self.loitering_guard: Optional[LoiteringGuard] = None
        self.motion_guard: Optional[MotionGuard] = None
        self.mqtt: Optional[MqttClient] = None
        self.object_analytics: Optional[ObjectAnalytics] = None
        self.params: Optional[Params] = None
        self.ports: Union[IoPortManagement, Ports, None] = None
        self.ptz: Optional[PtzControl] = None
        self.stream_profiles: Optional[StreamProfiles] = None
        self.user_groups: Optional[UserGroups] = None
        self.users: Optional[Users] = None
        self.view_areas: Optional[ViewAreas] = None
        self.vmd4: Optional[Vmd4] = None
コード例 #20
0
ファイル: test_auth.py プロジェクト: githubassets/httpx-1
def test_digest_auth_with_401():
    auth = httpx.DigestAuth(username="******", password="******")
    request = httpx.Request("GET", "https://www.example.com")

    # The initial request should not include an auth header.
    flow = auth.sync_auth_flow(request)
    request = next(flow)
    assert "Authorization" not in request.headers

    # If a 401 response is returned, then a digest auth request is made.
    headers = {
        "WWW-Authenticate":
        'Digest realm="...", qop="auth", nonce="...", opaque="..."'
    }
    response = httpx.Response(content=b"Auth required",
                              status_code=401,
                              headers=headers)
    request = flow.send(response)
    assert request.headers["Authorization"].startswith("Digest")

    # No other requests are made.
    response = httpx.Response(content=b"Hello, world!", status_code=200)
    with pytest.raises(StopIteration):
        flow.send(response)
コード例 #21
0
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
    """Set up the RESTful sensor."""
    await async_setup_reload_service(hass, DOMAIN, PLATFORMS)

    name = config.get(CONF_NAME)
    resource = config.get(CONF_RESOURCE)
    resource_template = config.get(CONF_RESOURCE_TEMPLATE)
    method = config.get(CONF_METHOD)
    payload = config.get(CONF_PAYLOAD)
    verify_ssl = config.get(CONF_VERIFY_SSL)
    username = config.get(CONF_USERNAME)
    password = config.get(CONF_PASSWORD)
    headers = config.get(CONF_HEADERS)
    params = config.get(CONF_PARAMS)
    unit = config.get(CONF_UNIT_OF_MEASUREMENT)
    device_class = config.get(CONF_DEVICE_CLASS)
    value_template = config.get(CONF_VALUE_TEMPLATE)
    json_attrs = config.get(CONF_JSON_ATTRS)
    json_attrs_path = config.get(CONF_JSON_ATTRS_PATH)
    force_update = config.get(CONF_FORCE_UPDATE)
    timeout = config.get(CONF_TIMEOUT)

    if value_template is not None:
        value_template.hass = hass

    if resource_template is not None:
        resource_template.hass = hass
        resource = resource_template.async_render(parse_result=False)

    if username and password:
        if config.get(CONF_AUTHENTICATION) == HTTP_DIGEST_AUTHENTICATION:
            auth = httpx.DigestAuth(username, password)
        else:
            auth = (username, password)
    else:
        auth = None
    rest = RestData(
        hass, method, resource, auth, headers, params, payload, verify_ssl, timeout
    )

    await rest.async_update()

    if rest.data is None:
        raise PlatformNotReady

    # Must update the sensor now (including fetching the rest resource) to
    # ensure it's updating its state.
    async_add_entities(
        [
            RestSensor(
                hass,
                rest,
                name,
                unit,
                device_class,
                value_template,
                json_attrs,
                force_update,
                resource_template,
                json_attrs_path,
            )
        ],
    )
コード例 #22
0
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    :   1_10_authentication.py
@Time    :   2021-02-23
@Author  :   EvilRecluse
@Contact :   https://github.com/RecluseXU
@Desc    :   授权验证
'''

# here put the import lib
import httpx

# 明文身份验证
# 2个元组的纯文本str或bytes对象作为auth参数传递给请求函数
httpx.get("https://example.com", auth=("my_user", "password123"))

# Digest 身份验证
auth = httpx.DigestAuth("my_user", "password123")
httpx.get("https://example.com", auth=auth)
コード例 #23
0
    select = config.get(CONF_SELECT)
    attr = config.get(CONF_ATTR)
    index = config.get(CONF_INDEX)
    unit = config.get(CONF_UNIT_OF_MEASUREMENT)
    device_class = config.get(CONF_DEVICE_CLASS)
    state_class = config.get(CONF_STATE_CLASS)
    username = config.get(CONF_USERNAME)
    password = config.get(CONF_PASSWORD)

    if (value_template := config.get(CONF_VALUE_TEMPLATE)) is not None:
        value_template.hass = hass

    auth: httpx.DigestAuth | tuple[str, str] | None
    if username and password:
        if config.get(CONF_AUTHENTICATION) == HTTP_DIGEST_AUTHENTICATION:
            auth = httpx.DigestAuth(username, password)
        else:
            auth = (username, password)
    else:
        auth = None
    rest = RestData(hass, method, resource, auth, headers, None, payload,
                    verify_ssl)
    await rest.async_update()

    if rest.data is None:
        raise PlatformNotReady

    async_add_entities(
        [
            ScrapeSensor(
                rest,