How to use the requests.packages function in requests

To help you get started, we’ve selected a few requests examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github certbot / certbot / certbot-ci / certbot_integration_tests / utils / misc.py View on Github external
def check_until_timeout(url, attempts=30):
    """
    Wait and block until given url responds with status 200, or raise an exception
    after the specified number of attempts.
    :param str url: the URL to test
    :param int attempts: the number of times to try to connect to the URL
    :raise ValueError: exception raised if unable to reach the URL
    """
    try:
        import urllib3
        urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
    except ImportError:
        # Handle old versions of request with vendorized urllib3
        from requests.packages.urllib3.exceptions import InsecureRequestWarning
        requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

    for _ in range(attempts):
        time.sleep(1)
        try:
            if requests.get(url, verify=False).status_code == 200:
                return
        except requests.exceptions.ConnectionError:
            pass

    raise ValueError('Error, url did not respond after {0} attempts: {1}'.format(attempts, url))
github mazen160 / struts-pwn_CVE-2018-11776 / struts-pwn.py View on Github external
# https://github.com/jas502n/St2-057
# *****************************************************

import argparse
import random
import requests
import sys
try:
    from urllib import parse as urlparse
except ImportError:
    import urlparse

# Disable SSL warnings
try:
    import requests.packages.urllib3
    requests.packages.urllib3.disable_warnings()
except Exception:
    pass

if len(sys.argv) <= 1:
    print('[*] CVE: 2018-11776 - Apache Struts2 S2-057')
    print('[*] Struts-PWN - @mazen160')
    print('\n%s -h for help.' % (sys.argv[0]))
    exit(0)


parser = argparse.ArgumentParser()
parser.add_argument("-u", "--url",
                    dest="url",
                    help="Check a single URL.",
                    action='store')
parser.add_argument("-l", "--list",
github 0xInfection / TIDoS-Framework / modules / ActiveRecon / passbrute.py View on Github external
#Author: @_tID
#This module requires TIDoS Framework
#https://github.com/the-Infected-Drake/TIDoS-Framework 

import os
import time
import requests
import sys
import FileUtils
sys.path.append('lib/FileUtils/')
from FileUtils import *
from colors import *
from requests.packages.urllib3.exceptions import InsecureRequestWarning

requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
file_paths = []
dir_path = []

def check0x00(web, dirpath, headers):

	try:
		for dirs in dirpath:
			web0x00 = web + dirs
			req = requests.get(web0x00, headers=headers, allow_redirects=False, timeout=7, verify=False)
			try:
			    if (req.headers['content-length'] is not None):
				size = int(req.headers['content-length'])
			    else:
				size = 0 
				
			except (KeyError, ValueError, TypeError):
github NCI-GDC / gdc-client / gdc_client / parcel / utils.py View on Github external
import logging
import mmap
import os
import requests
import stat
import sys

from progressbar import ProgressBar, Percentage, Bar, ETA, FileTransferSpeed


# Logging
log = logging.getLogger('utils')

# Silence warnings from requests
try:
    requests.packages.urllib3.disable_warnings()
except Exception as e:
    log.debug('Unable to silence requests warnings: {0}'.format(str(e)))


def check_transfer_size(actual, expected):
    """Simple validation on any expected versus actual sizes.

    :param int actual: The size that was actually transferred
    :param int actual: The size that was expected to be transferred

    """

    return actual == expected


def get_pbar(file_id, maxval, start_val=0):
github the-kid89 / pyem7 / pyem7 / base_api.py View on Github external
def set_connection(cls, user_name, password, end_point, session_verify):
        """Setting the connection settings for the API server.

            :param user_name: the API accounts user name
            :param password: the API account password
            :param end_point: the API's URL/end point
            :param session_verify: if you want to check the API cert or not
        """
        if not session_verify:
            requests.packages.urllib3.disable_warnings()

        cls.user_name = user_name
        cls.password = password
        cls.end_point = end_point

        cls.session = requests.Session()
        cls.session.auth = HTTPBasicAuth(user_name, password)
        cls.session.verify = session_verify
github demisto / content / Integrations / Cybereason / Cybereason.py View on Github external
import time
import re
import sys

# Define utf8 as default encoding
reload(sys)
sys.setdefaultencoding('utf8')  # pylint: disable=maybe-no-member

if not demisto.params()['proxy']:
    del os.environ['HTTP_PROXY']
    del os.environ['HTTPS_PROXY']
    del os.environ['http_proxy']
    del os.environ['https_proxy']

# disable insecure warnings
requests.packages.urllib3.disable_warnings()

''' GLOBAL VARS '''
SERVER = demisto.params()['server'][:-1] if demisto.params()['server'].endswith('/') else demisto.params()['server']
USERNAME = demisto.params().get('credentials').get('identifier')
PASSWORD = demisto.params().get('credentials').get('password')
USE_SSL = not demisto.params().get('unsecure', False)
CERTIFICATE = demisto.params().get('credentials').get('credentials').get('sshkey')
FETCH_TIME_DEFAULT = '3 days'
FETCH_TIME = demisto.params().get('fetch_time', FETCH_TIME_DEFAULT)
FETCH_TIME = FETCH_TIME if FETCH_TIME and FETCH_TIME.strip() else FETCH_TIME_DEFAULT
FETCH_BY = demisto.params().get('fetch_by', 'MALOP CREATION TIME')

STATUS_MAP = {
    'To Review': 'TODO',
    'Remediated': 'CLOSED',
    'Unread': 'UNREAD',
github CiscoDevNet / restconf-examples / restconf-102 / get_interfaces.py View on Github external
#!/usr/bin/python
#
# Get configured interfaces using RESTconf
#
# darien@sdnessentials.com
#
import requests
import sys


requests.packages.urllib3.disable_warnings()

HOST = 'ios-xe-mgmt.cisco.com'
PORT = 9443
USER = 'root'
PASS = 'C!sc0123'


def get_configured_interfaces():
    """Retrieving state data (routes) from RESTCONF."""
    url = "http://{h}:{p}/api/running/interfaces".format(h=HOST, p=PORT)
    # RESTCONF media types for REST API headers
    headers = {'Content-Type': 'application/vnd.yang.data+json',
               'Accept': 'application/vnd.yang.data+json'}
    # this statement performs a GET on the specified url
    response = requests.get(url, auth=(USER, PASS),
                            headers=headers, verify=False)
github StackStorm-Exchange / stackstorm-orion / actions / lib / actions.py View on Github external
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import time

from st2common.runners.base_action import Action
from orionsdk import SwisClient

from lib.node import OrionNode
from lib.utils import send_user_error, is_ip

# Silence ssl warnings
import requests
requests.packages.urllib3.disable_warnings()  # pylint: disable=no-member


class OrionBaseAction(Action):
    def __init__(self, config):
        super(OrionBaseAction, self).__init__(config)

        self.client = None

        if "orion_host" not in self.config:
            raise ValueError("Orion host details not in the config.yaml")
        elif "orion_user" not in self.config:
            raise ValueError("Orion user details not in the config.yaml")
        elif "orion_password" not in self.config:
            raise ValueError("Orion password details not in the config.yaml")

    def connect(self):
github icon-project / icon_cli_tool / icxcli / icx / wallet / __init__.py View on Github external
import os
import codecs

from eth_keyfile import create_keyfile_json, extract_key_from_keyfile
from icxcli.icx import FilePathIsWrong, PasswordIsNotAcceptable, NoPermissionToWriteFile, FileExists, \
    PasswordIsWrong, FilePathWithoutFileName, NetworkIsInvalid
from icxcli.icx import WalletInfo
from icxcli.icx import utils
from icxcli.icx import IcxSigner
from icxcli.icx.utils import get_address_by_privkey, get_timestamp_us, get_tx_hash, sign, \
    create_jsonrpc_request_content, validate_address, get_payload_of_json_rpc_get_balance, \
    check_balance_enough, check_amount_and_fee_is_valid, validate_key_store_file, validate_address_is_not_same
from icxcli.icx.utils import post

import requests
requests.packages.urllib3.disable_warnings()


def create_wallet(password, file_path):

    """ Create a wallet file with given wallet name, password and file path.

    :param password:  Password including alphabet character, number, and special character.
    If the user doesn't give password with -p, then CLI will show the prompt and user need to type the password.
    :param file_path: File path for the keystore file of the wallet.

    :return: Instance of WalletInfo class.
    """
    if not utils.validate_password(password):
        raise PasswordIsNotAcceptable

    key_store_contents = __make_key_store_content(password)
github cubewise-code / tm1py / TM1py.py View on Github external
def _disable_http_warnings(self):
        # disable HTTP verification warnings from requests library
        requests.packages.urllib3.disable_warnings()