Python requests.auth.HTTPDigestAuth() Examples

The following are 30 code examples of requests.auth.HTTPDigestAuth(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module requests.auth , or try the search function .
Example #1
Source File: HTTP.py    From watchdog with Apache License 2.0 7 votes vote down vote up
def setAuthMethod(self, auth_method):
        "Set the authentication method to use for the requests."
        self.auth_method = auth_method
        if len(self.auth_credentials) == 2:
            username, password = self.auth_credentials
            if self.auth_method == "basic":
                from requests.auth import HTTPBasicAuth
                self.h.auth = HTTPBasicAuth(username, password)
            elif self.auth_method == "digest":
                from requests.auth import HTTPDigestAuth
                self.h.auth = HTTPDigestAuth(username, password)
            elif self.auth_method == "ntlm":
                from requests_ntlm import HttpNtlmAuth
                self.h.auth = HttpNtlmAuth(username, password)
        elif self.auth_method == "kerberos":
            from requests_kerberos import HTTPKerberosAuth
            self.h.auth = HTTPKerberosAuth() 
Example #2
Source File: HTTP.py    From watchdog with Apache License 2.0 7 votes vote down vote up
def setAuthMethod(self, auth_method):
        "Set the authentication method to use for the requests."
        self.auth_method = auth_method
        if len(self.auth_credentials) == 2:
            username, password = self.auth_credentials
            if self.auth_method == "basic":
                from requests.auth import HTTPBasicAuth
                self.h.auth = HTTPBasicAuth(username, password)
            elif self.auth_method == "digest":
                from requests.auth import HTTPDigestAuth
                self.h.auth = HTTPDigestAuth(username, password)
            elif self.auth_method == "ntlm":
                from requests_ntlm import HttpNtlmAuth
                self.h.auth = HttpNtlmAuth(username, password)
        elif self.auth_method == "kerberos":
            from requests_kerberos import HTTPKerberosAuth
            self.h.auth = HTTPKerberosAuth() 
Example #3
Source File: DigestDefault.py    From Industrial-Security-Auditing-Framework with GNU General Public License v3.0 6 votes vote down vote up
def target_function(self, url, user, password):
        name = threading.current_thread().name

        user = user.encode('utf-8').strip()
        password = password.encode('utf-8').strip()

        response = http_request(method="GET", url=url, auth=HTTPDigestAuth(user, password))

        if response is not None and response.status_code != 401:
            print_success("Target: {}:{} {}: Authentication Succeed - Username: '{}' Password: '{}'"
                          .format(self.target, self.port, name, user, password), verbose=self.verbosity)
            self.credentials.append((self.target, self.port, user, password))
            if self.stop_on_success:
                raise Threads.StopThreadPoolExecutor
        else:
            print_error("Target: {}:{} {}: Authentication Failed - Username: '{}' Password: '{}'"
                        .format(self.target, self.port, name, user, password), verbose=self.verbosity) 
Example #4
Source File: auth.py    From PYHPEIMC with Apache License 2.0 6 votes vote down vote up
def get_auth(self):
        """
        This method requests an authentication object from the HPE IMC NMS and returns an HTTPDigest Auth Object
        :return:
        """
        url = self.h_url + self.server + ":" + self.port
        auth = requests.auth.HTTPDigestAuth(self.username,self.password)
        auth_url = "/imcrs"
        f_url = url + auth_url
        try:
            r = requests.get(f_url, auth=auth, headers=headers, verify=False)
            return r.status_code
    # checks for reqeusts exceptions
        except requests.exceptions.RequestException as e:
            return ("Error:\n" + str(e) + '\n\nThe IMC server address is invalid. Please try again')
            set_imc_creds()
        if r.status_code != 200:  # checks for valid IMC credentials
            return ("Error:\n" + str(e) +"Error: \n You're credentials are invalid. Please try again\n\n")
            set_imc_creds() 
Example #5
Source File: auth.py    From PYHPEIMC with Apache License 2.0 6 votes vote down vote up
def __init__(self, h_url,server,port,username, password):
        """
        Initializes the class. Set the h_url, server, username, and password variables.
        :param h_url: str value. Must be equal to "http://" or "https://
        :param server: str value. Must be valid IPv4 address or FQDN
        :param port: str value. Equal to listening port of IMC server. example "8080" for http or "8443" for HTTPS
        :param username: str value. Equal to username of IMC operator with privileges to access RESTUL API
        :param password: str value. Equal to valid password of username defined above
        :return:
        returns HTTPDigestauth object
        """
        super(HTTPDigestAuth,self).__init__()
        self.h_url = h_url
        self.server = server
        self.port = port
        self.username = username
        self.password = password
        self.url = self.h_url + self.server + ":" + self.port
        self.creds = requests.auth.HTTPDigestAuth(self.username, self.password) 
Example #6
Source File: auth.py    From PYHPEIMC with Apache License 2.0 6 votes vote down vote up
def get_auth(self):
        """
        This method requests an authentication object from the HPE IMC NMS and returns an HTTPDigest Auth Object
        :return:
        """
        url = self.h_url + self.server + ":" + self.port
        auth = requests.auth.HTTPDigestAuth(self.username,self.password)
        auth_url = "/imcrs"
        f_url = url + auth_url
        try:
            r = requests.get(f_url, auth=auth, headers=headers, verify=False)
            return r.status_code
    # checks for reqeusts exceptions
        except requests.exceptions.RequestException as e:
            return ("Error:\n" + str(e) + '\n\nThe IMC server address is invalid. Please try again')
            set_imc_creds()
        if r.status_code != 200:  # checks for valid IMC credentials
            return ("Error:\n" + str(e) +"Error: \n You're credentials are invalid. Please try again\n\n")
            set_imc_creds() 
Example #7
Source File: auth.py    From PYHPEIMC with Apache License 2.0 6 votes vote down vote up
def __init__(self, h_url,server,port,username, password):
        """
        Initializes the class. Set the h_url, server, username, and password variables.
        :param h_url: str value. Must be equal to "http://" or "https://
        :param server: str value. Must be valid IPv4 address or FQDN
        :param port: str value. Equal to listening port of IMC server. example "8080" for http or "8443" for HTTPS
        :param username: str value. Equal to username of IMC operator with privileges to access RESTUL API
        :param password: str value. Equal to valid password of username defined above
        :return:
        returns HTTPDigestauth object
        """
        super(HTTPDigestAuth,self).__init__()
        self.h_url = h_url
        self.server = server
        self.port = port
        self.username = username
        self.password = password
        self.url = self.h_url + self.server + ":" + self.port
        self.creds = requests.auth.HTTPDigestAuth(self.username, self.password) 
Example #8
Source File: authids.py    From lethean-vpn with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def walletJSONCall(self, method, params):
        d = {
            "id": "0",
            "method": method,
            "jsonrpc": "2.0",
            "params": params
        }
        url = config.CONFIG.CAP.walletUri
        log.L.debug("Calling wallet RPC " + url)
        try:
            r = requests.post(url, data=json.dumps(d), auth=HTTPDigestAuth(config.CONFIG.CAP.walletUsername, config.CONFIG.CAP.walletPassword), headers={"Content-Type": "application/json"})
            if (r.status_code == 200):
                j = json.loads(r.text)
                if ('result' in j):
                    return(r.text)
                else:
                    log.L.error("Wallet RPC error %s! Will not receive payments!" % (r.text))
                    return(None)
            else:
                log.L.error("Wallet RPC error %s! Will not receive payments!" % (r.status_code))
                return(None)
        except IOError:
            return(None) 
Example #9
Source File: client.py    From networking-odl with Apache License 2.0 6 votes vote down vote up
def _get_req_params(self, params):
        req_params = {
            'headers': {
                'Accept': 'application/json'
            },
            'timeout': self.conf.http_timeout,
        }

        auth_way = params.get('auth')
        if auth_way in ['basic', 'digest']:
            user = params.get('user')
            password = params.get('password')

            if auth_way == 'basic':
                auth_class = auth.HTTPBasicAuth
            else:
                auth_class = auth.HTTPDigestAuth

            req_params['auth'] = auth_class(user, password)
        return req_params 
Example #10
Source File: DigestBruteforce.py    From Industrial-Security-Auditing-Framework with GNU General Public License v3.0 6 votes vote down vote up
def target_function(self, url, creds):
        name = threading.current_thread().name
        user, password = creds
        user = user.encode('utf-8').strip()
        password = password.encode('utf-8').strip()

        response = http_request(method="GET", url=url, auth=HTTPDigestAuth(user, password))

        if response is not None and response.status_code != 401:
            print_success("Target: {}:{} {}: Authentication Succeed - Username: '{}' Password: '{}'".format(self.target,
                                                                                                            self.port,
                                                                                                            name, user,
                                                                                                            password),
                          verbose=self.verbosity)
            self.credentials.append((self.target, self.port, user, password))
            if self.stop_on_success:
                raise Threads.StopThreadPoolExecutor
        else:
            print_error(
                "Target: {}:{} {}: Authentication Failed - Username: '{}' Password: '{}'".format(self.target, self.port,
                                                                                                 name, user, password),
                verbose=self.verbosity) 
Example #11
Source File: crawler.py    From ITWSV with MIT License 6 votes vote down vote up
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
            if self._auth_method == "basic":
                from requests.auth import HTTPBasicAuth
                self._session.auth = HTTPBasicAuth(username, password)
            elif self._auth_method == "digest":
                from requests.auth import HTTPDigestAuth
                self._session.auth = HTTPDigestAuth(username, password)
            elif self._auth_method == "ntlm":
                from requests_ntlm import HttpNtlmAuth
                self._session.auth = HttpNtlmAuth(username, password)
        elif self._auth_method == "kerberos":
            # On openSUSE, "zypper in krb5-devel" before installing the pip package
            from requests_kerberos import HTTPKerberosAuth
            self._session.auth = HTTPKerberosAuth() 
Example #12
Source File: client.py    From rets with MIT License 6 votes vote down vote up
def _get_http_auth(username: str, password: str, auth_type: str) -> AuthBase:
    if auth_type == 'basic':
        return HTTPBasicAuth(username, password)
    if auth_type == 'digest':
        return HTTPDigestAuth(username, password)
    raise RetsClientError('unknown auth type %s' % auth_type) 
Example #13
Source File: pylips.py    From pylips with MIT License 6 votes vote down vote up
def get(self, path, verbose=True, err_count=0):
        while err_count < int(self.config["DEFAULT"]["num_retries"]):
            if verbose:
                print("Sending GET request to", str(self.config["TV"]["protocol"]) + str(self.config["TV"]["host"]) + ":" + str(self.config["TV"]["port"]) + "/" + str(self.config["TV"]["apiv"]) + "/" + str(path))
            try:
                r = session.get(str(self.config["TV"]["protocol"]) + str(self.config["TV"]["host"]) + ":" + str(self.config["TV"]["port"]) + "/" + str(self.config["TV"]["apiv"]) + "/" + str(path), verify=False, auth=HTTPDigestAuth(str(self.config["TV"]["user"]), str(self.config["TV"]["pass"])), timeout=2)
            except Exception:
                err_count += 1
                continue
            if verbose:
                print("Request sent!")
            if len(r.text) > 0:
                print(r.text)
                return r.text
        else:
            if self.config["DEFAULT"]["mqtt_listen"].lower()=="true":
                self.mqtt_update_status({"powerstate":"Off", "volume":None, "muted":False, "cur_app":None, "ambilight":None, "ambihue":False})
            return json.dumps({"error":"Can not reach the API"})

    # sends a general POST request 
Example #14
Source File: pylips.py    From pylips with MIT License 6 votes vote down vote up
def pair_confirm(self, data, err_count=0):
        while err_count < 10:
            if err_count > 0:
                print("Resending pair confirm request")
            try:
                # print(data)
                r = session.post("https://" + str(self.config["TV"]["host"]) +":1926/"+str(self.config["TV"]["apiv"])+"/pair/grant", json=data, verify=False, auth=HTTPDigestAuth(self.config["TV"]["user"], self.config["TV"]["pass"]),timeout=2)
                print (r.request.headers)
                print (r.request.body)
                print("Username for subsequent calls is: " + str(self.config["TV"]["user"]))
                print("Password for subsequent calls is: " + str(self.config["TV"]["pass"]))
                return print("The credentials are saved in the settings.ini file.")
            except Exception:
                # try again
                err_count += 1
                continue
        else:
            return print("The API is unreachable. Try restarting your TV and pairing again")

    # sends a general GET request 
Example #15
Source File: util.py    From autosuspend with GNU General Public License v2.0 5 votes vote down vote up
def request(self) -> "requests.model.Response":
        import requests
        from requests.auth import HTTPBasicAuth, HTTPDigestAuth
        import requests.exceptions

        auth_map = {
            "basic": HTTPBasicAuth,
            "digest": HTTPDigestAuth,
        }

        session = requests.Session()
        try:
            from requests_file import FileAdapter

            session.mount("file://", FileAdapter())
        except ImportError:
            pass

        try:
            reply = session.get(self._url, timeout=self._timeout)

            # replace reply with an authenticated version if credentials are
            # available and the server has requested authentication
            if self._username and self._password and reply.status_code == 401:
                auth_scheme = reply.headers["WWW-Authenticate"].split(" ")[0].lower()
                if auth_scheme not in auth_map:
                    raise SevereCheckError(
                        "Unsupported authentication scheme {}".format(auth_scheme)
                    )
                auth = auth_map[auth_scheme](self._username, self._password)
                reply = session.get(self._url, timeout=self._timeout, auth=auth)

            reply.raise_for_status()
            return reply
        except requests.exceptions.RequestException as error:
            raise TemporaryCheckError(error) from error 
Example #16
Source File: Command.py    From calvin-base with Apache License 2.0 5 votes vote down vote up
def get_auth_method(auth):
        if auth.get("authtype") == "basic":
            auth = HTTPBasicAuth(auth.get("username"), auth.get("password"))
        elif auth.get("authtype") == "digest":
            auth = HTTPDigestAuth(auth.get("username"), auth.get("password"))
        else:
            _log.warning("Ignoring unknown authentication method {}".format(auth.get("authtype")))
            auth = None

        return auth 
Example #17
Source File: webclient.py    From scrapy-do with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def request(method, url, payload={}, auth=None, ssl_verify=True):
    """
    Send a request to the server and retrieva the response.

    :param method:                            request method ('POST' or 'GET')
    :param url:                               url to be queried
    :param payload:                           parameters of the request
    :param auth:                              tuple containing the authorization
                                              information
    :param ssl_verify:                        SSL verification flag
    :raises scrapy_do.client.ClientException: an error
    :return:                                  parsed JSON response of the server
                                              or raw data
    """
    assert method == 'POST' or method == 'GET'

    if not ssl_verify:
        urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

    if auth is not None:
        auth = HTTPDigestAuth(*auth)

    try:
        if method == 'POST':
            r = requests.post(url, data=payload, auth=auth, verify=ssl_verify)
        else:
            r = requests.get(url, params=payload, auth=auth, verify=ssl_verify)
    except Exception as e:
        raise ClientException(str(e))

    if r.headers['Content-Type'] == 'application/json':
        data = r.json()
    else:
        data = r.text

    if r.status_code != 200:
        if r.headers['Content-Type'] == 'application/json':
            raise ClientException(data['msg'])
        else:
            raise ClientException(data)
    return data 
Example #18
Source File: http.py    From integrations-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def create_digest_auth(config):
    return requests_auth.HTTPDigestAuth(config['username'], config['password']) 
Example #19
Source File: http_digest_bruteforce.py    From isf with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def target_function(self, url, creds):
        name = threading.current_thread().name
        user, password = creds
        user = user.encode('utf-8').strip()
        password = password.encode('utf-8').strip()

        response = http_request(method="GET", url=url, auth=HTTPDigestAuth(user, password))

        if response is not None and response.status_code != 401:
            print_success("Target: {}:{} {}: Authentication Succeed - Username: '{}' Password: '{}'".format(self.target, self.port, name, user, password), verbose=self.verbosity)
            self.credentials.append((self.target, self.port, user, password))
            if self.stop_on_success:
                raise StopThreadPoolExecutor
        else:
            print_error("Target: {}:{} {}: Authentication Failed - Username: '{}' Password: '{}'".format(self.target, self.port, name, user, password), verbose=self.verbosity) 
Example #20
Source File: client.py    From amt with Apache License 2.0 5 votes vote down vote up
def vnc_status(self):
        payload = amt.wsman.get_request(
            self.uri,
            ('http://intel.com/wbem/wscim/1/ips-schema/1/'
             'IPS_KVMRedirectionSettingData'))
        resp = requests.post(self.uri,
                             auth=HTTPDigestAuth(self.username, self.password),
                             data=payload)
        resp.raise_for_status()
        return pp_xml(resp.content) 
Example #21
Source File: client.py    From amt with Apache License 2.0 5 votes vote down vote up
def power_status(self):
        payload = amt.wsman.get_request(
            self.uri,
            CIM_AssociatedPowerManagementService)
        resp = requests.post(self.uri,
                             auth=HTTPDigestAuth(self.username, self.password),
                             data=payload)
        resp.raise_for_status()
        value = _find_value(
            resp.content,
            CIM_AssociatedPowerManagementService,
            "PowerState")
        return value 
Example #22
Source File: http_digest_default.py    From isf with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def target_function(self, url, user, password):
        name = threading.current_thread().name

        user = user.encode('utf-8').strip()
        password = password.encode('utf-8').strip()

        response = http_request(method="GET", url=url, auth=HTTPDigestAuth(user, password))

        if response is not None and response.status_code != 401:
            print_success("Target: {}:{} {}: Authentication Succeed - Username: '{}' Password: '{}'".format(self.target, self.port, name, user, password), verbose=self.verbosity)
            self.credentials.append((self.target, self.port, user, password))
            if self.stop_on_success:
                raise StopThreadPoolExecutor
        else:
            print_error("Target: {}:{} {}: Authentication Failed - Username: '{}' Password: '{}'".format(self.target, self.port, name, user, password), verbose=self.verbosity) 
Example #23
Source File: soaper.py    From fritzconnection with MIT License 5 votes vote down vote up
def execute(self, service, action_name, arguments):
        """
        Builds the soap request and returns the response as dictionary.
        Numeric and boolean values are converted from strings to Python
        datatypes.
        """
        def handle_response(response):
            if response.status_code != 200:
                raise_fritzconnection_error(response)
            return self.parse_response(response, service, action_name)

        headers = self.headers.copy()
        headers['soapaction'] = f'{service.serviceType}#{action_name}'
        arguments = preprocess_arguments(arguments)
        arguments = ''.join(self.argument_template.format(name=k, value=v)
                            for k, v in arguments.items())
        body = self.get_body(service, action_name, arguments)
        envelope = self.envelope.format(body=body)
        url = f'{self.address}:{self.port}{service.controlURL}'
        if self.session:
            with self.session.post(
                url, data=envelope, headers=headers
            ) as response:
                return handle_response(response)
        else:
            if self.password:
                auth = HTTPDigestAuth(self.user, self.password)
            else:
                auth = None
            response = requests.post(
                url, data=envelope, headers=headers, auth=auth,
                timeout=self.timeout, verify=False
            )
            return handle_response(response) 
Example #24
Source File: es.py    From pmacct-to-elasticsearch with MIT License 5 votes vote down vote up
def http(CONFIG, url, method="GET", data=None):
    auth = None
    if CONFIG['ES_AuthType'] != 'none':
        if CONFIG['ES_AuthType'] == 'basic':
            auth = HTTPBasicAuth(CONFIG['ES_UserName'], CONFIG['ES_Password'])
        elif CONFIG['ES_AuthType'] == 'digest':
            auth = HTTPDigestAuth(CONFIG['ES_UserName'], CONFIG['ES_Password'])
        else:
            raise P2ESError(
                'Unexpected authentication type: {}'.format(CONFIG['ES_AuthType'])
            )

    headers = {'Content-Type': 'application/json'}

    if method == "GET":
        return requests.get(url, auth=auth, headers=headers)
    elif method == "POST":
        return requests.post(url, auth=auth, data=data, headers=headers)
    elif method == "PUT":
        return requests.put(url, auth=auth, data=data, headers=headers)
    elif method == "HEAD":
        return requests.head(url, auth=auth, headers=headers)
    else:
        raise Exception("Method unknown: {}".format(method))

# Sends data to ES.
# Raises exceptions: yes. 
Example #25
Source File: util.py    From dot15926 with GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self, uri, login=None, password=None):
        if login and password:
            self.session = requests.session(auth=HTTPDigestAuth(login, password))
        else:
            self.session = requests.session() 
Example #26
Source File: test_http.py    From integrations-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_config_digest_authtype(self):
        instance = {'username': 'user', 'password': 'pass', 'auth_type': 'digest'}
        init_config = {}
        http = RequestsWrapper(instance, init_config)
        assert isinstance(http.options['auth'], requests_auth.HTTPDigestAuth)

        with mock.patch('datadog_checks.base.utils.http.requests_auth.HTTPDigestAuth') as m:
            RequestsWrapper(instance, init_config)

            m.assert_called_once_with('user', 'pass') 
Example #27
Source File: client.py    From amt with Apache License 2.0 5 votes vote down vote up
def post(self, payload, ns=None):
        resp = requests.post(self.uri,
                             headers={'content-type':
                                      'application/soap+xml;charset=UTF-8'},
                             auth=HTTPDigestAuth(self.username, self.password),
                             data=payload)
        resp.raise_for_status()
        if ns:
            rv = _return_value(resp.content, ns)
            if rv == 0:
                return 0
            print(pp_xml(resp.content))
        else:
            return 0 
Example #28
Source File: util.py    From docassemble with MIT License 5 votes vote down vote up
def _get_auth(self, auth):
        if auth is None and hasattr(self, 'auth'):
            auth = self.auth
        if isinstance(auth, (dict, DADict)):
            if auth.get('type', 'basic') == 'basic':
                return HTTPBasicAuth(auth['username'], auth['password'])
            elif auth['type'] == 'digest':
                return HTTPDigestAuth(auth['username'], auth['password'])
        return auth 
Example #29
Source File: __init__.py    From pimotion with MIT License 5 votes vote down vote up
def __get(self, uri):
        headers = {'accept': 'application/json'}
        r = requests.get(uri, auth=HTTPDigestAuth(self.username, self.password),
                              headers=headers)
        if r.status_code != 200:
            raise CloudAppHttpError(response=r)
        return json.loads(r.text) 
Example #30
Source File: utils.py    From schemathesis with MIT License 5 votes vote down vote up
def get_requests_auth(auth: Optional[RawAuth], auth_type: Optional[str]) -> Optional[Union[HTTPDigestAuth, RawAuth]]:
    if auth and auth_type == "digest":
        return HTTPDigestAuth(*auth)
    return auth