Exemple #1
0
    def __call__(self, req):
        parsed = urlparse.urlparse(req.url)

        # Get the netloc without any embedded credentials
        netloc = parsed.netloc.split("@", 1)[-1]

        # Set the url of the request to the url without any credentials
        req.url = urlparse.urlunparse(parsed[:1] + (netloc,) + parsed[2:])

        # Use any stored credentials that we have for this netloc
        username, password = self.passwords.get(netloc, (None, None))

        # Extract credentials embedded in the url if we have none stored
        if username is None:
            username, password = self.parse_credentials(parsed.netloc)

        if username or password:
            # Store the username and password
            self.passwords[netloc] = (username, password)

            # Send the basic auth with this request
            req = HTTPBasicAuth(username or "", password or "")(req)

        # Attach a hook to handle 401 responses
        req.register_hook("response", self.handle_401)

        return req
Exemple #2
0
 def __call__(self, req):
   req = HTTPBasicAuth(self.username, self.getPassword())(req)
   auth = 'SPBP-SIGN v=0;f={fp};n={nonce};t={ts}'.format(
     fp=q(self.fingerprint), nonce=q(self.getNonce()), ts=time.time())
   sdata = '\n'.join([req.method.upper(), req.url, req.body or '', auth])
   auth += ';s=' + q(signData(sdata, self.getPrivateKey()))
   req.headers['x-spbp-authorization'] = auth
   return req
    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
Exemple #4
0
USERNAME = "******"
PASSWORD = "******"
VERIFY = True  # Set to True in Case of Cisco Sandbox ONLY

# Inputs 1
headers = {
    "Content-Type": "application/json",
    "Accept": "application/json",
}

# Processing 1
try:
    token_response = requests.post(
        url=f"{BASE_URL}/dna/system/api/v1/auth/token",
        headers=headers,
        auth=HTTPBasicAuth(USERNAME, PASSWORD),
        verify=VERIFY,
    )
    token_response.raise_for_status()
except Exception as ex:
    raise SystemExit(ex)

# Output 1
token = token_response.json()["Token"]

# ------------------------------------

# Inputs 2
headers_2 = {
    **headers,  # Using Spread Operator
    "X-Auth-Token": token,
def main():
    '''Entry point if called as an executable'''
    
    try:
        print "Create a request to fetch a pet:\n"
        myResponse = requests.get(url + "/pets/1", \
                                  auth=HTTPBasicAuth(user, password), \
                                  headers=headers, \
                                  timeout=timeout)
        output(myResponse)
    except requests.exceptions.RequestException as e:
        print e
    except ValueError as e:
        print msg_json_error, e
    # end try
    
    try:
        print "Create a request to add a pet:\n"
        data = {"name" : "zebra"}
        data_json = json.dumps(data)
        myResponse = requests.put(url + "/pets", \
                                  auth=HTTPBasicAuth(user, password), \
                                  data=data_json, \
                                  headers=headers, \
                                  timeout=timeout)
        output(myResponse)
        location = myResponse.headers['Location']
        print "Create a request to delete a pet:\n"
        print "location: " + location + "\n"
        myResponse = requests.delete(location, \
                                     auth=HTTPBasicAuth(user, password), \
                                     headers=headers, \
                                     timeout=timeout)
        output(myResponse)
    except requests.exceptions.RequestException as e:
        print e
    except ValueError as e:
        print msg_json_error, e
    # end try
    
    try:
        print "Create a request to do a simple health check:\n"
        myResponse = requests.get(url+'/admin/ping', \
                                  auth=HTTPBasicAuth(admin_user, admin_password), \
                                  timeout=timeout)
        output(myResponse)
    except requests.exceptions.RequestException as e:
        print e
    except ValueError as e:
        print msg_json_error, e
    # end try
    
    # the metadata block may be confusing python's JSON parser
    try:
        print "Create a request to fetch list of pets:\n"
        myResponse = requests.get(url + "/pets", \
                                  auth=HTTPBasicAuth(user, password), \
                                  headers=headers, \
                                  timeout=timeout)
        output(myResponse)
    except requests.exceptions.RequestException as e:
        print vars(myResponse)
        print e
    except ValueError as e:
        print vars(myResponse)
        print msg_json_error, e
    # end try
    
    exit(0)
Exemple #6
0
#!/usr/bin/python
# -*- coding: utf-8 -*-
import requests
import json
from requests.auth import HTTPBasicAuth

user = ""
api_key = ""
url = "" % user
pushover_token = ""
pushover_user_token = ""

my_info = requests.get(url, auth=HTTPBasicAuth(user, api_key)).content
my_balance = json.loads(my_info)["balances"]["BTC"]

current_price = requests.get('https://blockchain.info/ticker')
current_price_in_euro = json.loads(current_price.content)["EUR"]["last"]

value_in_euro = "%.10f" % (float(my_balance) * float(current_price_in_euro))

message = "€" + str(value_in_euro)

pushover_url = 'https://api.pushover.net/1/messages.json'
data = {
    'token': pushover_token,
    'user': pushover_user_token,
    'message': message
}

requests.post(pushover_url, data=data)
    else:
        kvs = "ece-health-settings"

    if not(appid and tenant and key and vbu):
        logging.critical("[---] you need to have the right evironment variables; looking for APPID, APPKEY, TENANT, RESOURCE, VAULT")
        exit()
     # initializing the secret helper
    sh = SecretHelper(client_id=appid, secret=key, tenant=tenant, resource=resource)
    # domain and documentdb settings
    conf = json.loads(sh.get_secret(vbu, kvs).value)
    # set up connection to ES
    logging.info("set up connection to ES")
    es=Elasticsearch(hosts=conf['logurl'])

    try:
        response = requests.get(url=conf['url']+"/api/v1/clusters/elasticsearch", auth=HTTPBasicAuth(conf['username'], conf['password']), verify=False)
        if response.status_code == 200:
            logging.info("ece api seems to work; status code: %d" % response.status_code)
            resp_dict = response.json()
            if resp_dict['return_count'] == 0:
                internal_teams_message("we have somehow managed to misplaced all the ElasticSearch clusters - time to freak out","Elastic Cloud Enterprise",conf['teams'], "DC143C")
                logging.critical("we have somehow managed to misplaced all the ElasticSearch clusters - time to freak out")

            else:
                esproblem = False
                for cluster in resp_dict['elasticsearch_clusters']:
                    logging.info("%s - %s" % (str(cluster['cluster_name']), str(cluster['plan_info']['healthy'])))
                    if not cluster['plan_info']['healthy']:
                        # let's figure out why it is unhealthy
                        if not cluster['elasticsearch']['healthy']:
                            message = "cluster %s is unhealthy because of elasticsearch" % (cluster['cluster_name'])
Exemple #8
0
 def set_credentials(self, username, password):
     """ Set the username and password for the current session"""
     auth = HTTPBasicAuth(username, password)
     self.s.auth = auth
#!/usr/bin/python3
"""
Dysplay id based on credentials
"""
if __name__ == '__main__':
    import requests
    from requests.auth import HTTPBasicAuth
    from sys import argv
    r = requests.get('https://api.github.com/users/{}'.format(argv[1]),
                     auth=HTTPBasicAuth(argv[1], argv[2]))
    print(r.json().get('id'))
Exemple #10
0
      (username, password, root))

if None in [username, password, root]:
    raise Exception("Define variables in ./conf.yaml. Exiting.")

# Specify file location of an SOW.
location = "/Users/vishall/prog/assess-root/test2.pdf"
file = {"pdf": open(location, "rb")}

# Recommend SoW given text "Example text about airplanes.".
print("Sending GET request to `/recommend_text`.")
jsonLoad = {"text_field": "Example text about airplanes"}
r = requests.post(
    f"{root}/recommend_text?size=1",
    json=jsonLoad,
    auth=HTTPBasicAuth(username, password),
)
pp.pprint(r.text)

# Recommend an SoW given a PDF.
print("Sending GET request to `/recommend_file` with a PDF.")
r = requests.post(f"{root}/recommend_file",
                  files=file,
                  auth=HTTPBasicAuth(username, password))
pp.pprint(r.text)

# Extract standard reference from PDF.
print("Sending POST request to `/extract` using a PDF.")
r = requests.post(f"{root}/extract",
                  files=file,
                  auth=HTTPBasicAuth(username, password))
Exemple #11
0
    def fetch_access_token(self,
                           url=None,
                           code=None,
                           authorization_response=None,
                           body='',
                           auth=None,
                           username=None,
                           password=None,
                           method='POST',
                           headers=None,
                           timeout=None,
                           verify=True,
                           proxies=None,
                           **kwargs):
        """Generic method for fetching an access token from the token endpoint.

        :param url: Access Token endpoint URL, if not configured,
                    ``authorization_response`` is used to extract token from
                    its fragment (implicit way).
        :param code: Authorization code (if any)
        :param authorization_response: Authorization response URL, the callback
                                       URL of the request back to you. We can
                                       extract authorization code from it.
        :param body: Optional application/x-www-form-urlencoded body to add the
                     include in the token request. Prefer kwargs over body.
        :param auth: An auth tuple or method as accepted by requests.
        :param username: Username used by legacy clients.
        :param password: Password used by legacy clients.
        :param method: The HTTP method used to make the request. Defaults
                       to POST, but may also be GET. Other methods should
                       be added as needed.
        :param headers: Dict to default request headers with.
        :param timeout: Timeout of the request in seconds.
        :param verify: Verify SSL certificate.
        :param proxies: Proxies to use with requests.
        :param kwargs: Extra parameters to include in the token request.
        :return: A :class:`OAuth2Token` object (a dict too).
        """
        if url is None and authorization_response:
            return self.token_from_fragment(authorization_response)

        InsecureTransportError.check(url)

        body = self._prepare_authorization_code_body(code,
                                                     authorization_response,
                                                     body, **kwargs)

        if auth is None:
            if username and password:
                auth = HTTPBasicAuth(username, password)
            else:
                client_secret = self.client_secret
                if client_secret is None:
                    client_secret = ''
                auth = HTTPBasicAuth(self.client_id, client_secret)

        if headers is None:
            headers = DEFAULT_HEADERS

        if method.upper() == 'POST':
            resp = self.post(
                url,
                data=dict(url_decode(body)),
                timeout=timeout,
                headers=headers,
                auth=auth,
                verify=verify,
                proxies=proxies,
                withhold_token=True,
            )
        else:
            resp = self.get(
                url,
                params=dict(url_decode(body)),
                timeout=timeout,
                headers=headers,
                auth=auth,
                verify=verify,
                proxies=proxies,
                withhold_token=True,
            )

        for hook in self.compliance_hook['access_token_response']:
            resp = hook(resp)

        params = resp.json()
        return self._parse_and_validate_token(params, resp.status_code)
Exemple #12
0
def get_balance(login, password):
    answer = requests.get('http://stonks.goto.msk.ru/api/robot/balance/', auth=HTTPBasicAuth(login, password))
    answer = answer.json()
    return round(answer['balance'], 3)
Exemple #13
0
    def _do_api_call(self,
                     endpoint_info: Tuple[str, str],
                     json: Optional[Dict[str, Any]] = None):
        """
        Utility function to perform an API call with retries

        :param endpoint_info: Tuple of method and endpoint
        :param json: Parameters for this API call.
        :return: If the api call returns a OK status code,
            this function returns the response in JSON. Otherwise,
            we throw an AirflowException.
        :rtype: dict
        """
        method, endpoint = endpoint_info

        # TODO: get rid of explicit 'api/' in the endpoint specification
        url = f'https://{self.host}/{endpoint}'

        aad_headers = self._get_aad_headers()
        headers = {**USER_AGENT_HEADER.copy(), **aad_headers}

        auth: AuthBase
        token = self._get_token()
        if token:
            auth = _TokenAuth(token)
        else:
            self.log.info('Using basic auth.')
            auth = HTTPBasicAuth(self.databricks_conn.login,
                                 self.databricks_conn.password)

        request_func: Any
        if method == 'GET':
            request_func = requests.get
        elif method == 'POST':
            request_func = requests.post
        elif method == 'PATCH':
            request_func = requests.patch
        else:
            raise AirflowException('Unexpected HTTP Method: ' + method)

        try:
            for attempt in self._get_retry_object():
                with attempt:
                    response = request_func(
                        url,
                        json=json if method in ('POST', 'PATCH') else None,
                        params=json if method == 'GET' else None,
                        auth=auth,
                        headers=headers,
                        timeout=self.timeout_seconds,
                    )
                    response.raise_for_status()
                    return response.json()
        except RetryError:
            raise AirflowException(
                f'API requests to Databricks failed {self.retry_limit} times. Giving up.'
            )
        except requests_exceptions.HTTPError as e:
            raise AirflowException(
                f'Response: {e.response.content}, Status Code: {e.response.status_code}'
            )
Exemple #14
0
# IFTTT Config
event = "IFTTT_EVENT"
key = "IFTTT_KEY"
# ----------------------

# Init VRC API
API_BASE = "https://api.vrchat.cloud/api/1"

url = "{}/config".format(API_BASE)
response = requests.get(url)
apiKey = json.loads(response.text)["clientApiKey"]

url = "{}/auth/user".format(API_BASE)
response = requests.get(url,
                        params={"apiKey": apiKey},
                        auth=HTTPBasicAuth(USER, PASSWORD))
token = response.cookies["auth"]

# Let's Just H!
JUST_WORLD_ID = "wrld_e0e29017-9061-432f-b3d7-b2005dc323fc"
url = "{}/worlds/{}".format(API_BASE, JUST_WORLD_ID)
response = requests.get(url, params={"apiKey": apiKey, "authToken": token})
previousPrivateOccupants = response.json()["privateOccupants"]

# Init IFTTT
ifttt_url = "https://maker.ifttt.com/trigger/{}/with/key/{}".format(event, key)
params = {"value1": ""}

# TImer
base_time = time.time()
next_time = 0
from requests.auth import HTTPBasicAuth
from datetime import datetime, timedelta
from .database import db

# set up our logger utility
logger = get_task_logger(__name__)

# generate a list of messages for the console
filename = os.getcwd()
messages = [line.rstrip("\n") for line in open(filename + "/stalks/messages1.txt")]

# base objects

SNOW_BASE_URL = "dev73949.service-now.com/api/x_328385_restapi/bbi/"
API_METHOD = "GET"
auth = HTTPBasicAuth("", "")
hdrs = {"Content-Type": "application/json", "Accept": "application/json"}


@task(queue="messages", max_retries=3)
def log(message):
    """Print some log messages"""
    logger.warning(message)
    return str(message)


@task(queue="locations", max_retries=3)
def get_locations():
    """
    Get the list of Active BBI Locations
    :param: None
Exemple #16
0
URL = "https://sandboxdnac.cisco.com/api/system/v1/auth/token"

#Create dictionary for the resposne payload, headers, in this we are doing an http post
#so we need to specify the content type we are sending rather than accepting a format

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

#creates a response variable with the value of our post request notice this is a post not a get
#which is different than what we have been doing so far we are sending the server something not
#asking for it.  Also note we are passing a username and password and lastly as you will notice
#in the next lab we have set verify to false this is because DNA Center is using a self signed
#certificate and we are aware so we want to accept the risk and continue
#THIS SHOULD NOT BE DONE IN A PRODUCTION ENVIRONMENT IT IS A SECURITY ISSUE!!!!

response = requests.post(URL,
                         auth=HTTPBasicAuth(USER, PASS),
                         headers=headers,
                         verify=False)

#converts our respone to json format and stores it in our variable resposneJSON

token = response.json()['Token']

#prints responseJSON variable

#print("Your generated token is: " + token)

#Creates a variable URL2 and assigns the value of the follow up API request
#to DNA Center to retrieve a list of network devices

URL2 = "https://sandboxdnac.cisco.com/dna/intent/api/v1/network-device"
Exemple #17
0
import dash
import dash_core_components as dcc
import dash_html_components as html
import requests as req
import time
from configparser import ConfigParser
from flask_caching import Cache
from requests.auth import HTTPBasicAuth


app = dash.Dash(__name__)

cfg = ConfigParser()
cfg.read('./config.ini')
host = cfg['SQDash']['host']
auth=HTTPBasicAuth(cfg['SQDash']['username'], cfg['SQDash']['password'])
componentStatusUpdated = time.time()
componentStatusUpdateCycle = 300

cache = Cache(app.server, config={
    'CACHE_TYPE': 'filesystem',
    'CACHE_DIR': 'cache-directory'
})


@cache.memoize(3600)
def get_components():
    timeStart = time.time()
    res = req.get("%s/api/components/search?qualifiers=TRK" % host, auth=auth)
    components={}
    for component in res.json()['components']:
Exemple #18
0
import telebot
from telebot import TeleBot, types
from random import randint
import requests
import time
from requests.auth import HTTPBasicAuth

answer = requests.get('http://stonks.goto.msk.ru/api/robot/stocks/', auth=HTTPBasicAuth('fathutnik', 'Superpapa1'))

token = ""
# Обходим блокировку с помощью прокси
# telebot.apihelper.proxy = {'https': 'socks5h://geek:[email protected]:7777'}
# подключаемся к телеграму
bot = telebot.TeleBot(token=token)

pictures = {
    0: "https://avatars.mds.yandex.net/get-zen_doc/1661927/pub_5e5010916617c37cfdda1c23_5e501233f2bc623242237b29/scale_1200",
}
states = {}
inventories = {}
user_id = []
state = 1
real_news_ad = []
ans = None
login = '******'


@bot.message_handler(commands=["start"])
def start_game(message):
    user = message.chat.id
    user_id.append(message.from_user.id)
Exemple #19
0
 def get_inbox(self):
     r = requests.get(self.url + 'messages',
                      auth=HTTPBasicAuth(self.token, ''))
     if r.status_code == requests.codes.ok:
         return r.json()['messages']
     return False
#!/usr/bin/python3
"""
a Python script that takes your Github credentials (username and password)
and uses the Github API to display your id
"""
import requests
from requests.auth import HTTPBasicAuth
import sys

if __name__ == '__main__':
    url = 'https://api.github.com/user'
    r = requests.get(url, auth=HTTPBasicAuth(sys.argv[1], sys.argv[2]))
    r = requests.get(url, auth=(sys.argv[1], sys.argv[2]))
    try:
        print(r.json()['id'])
    except:
        print('None')
Exemple #21
0
 def get_messages_from_user(self, id):
     r = requests.get(self.url + 'messages/' + str(id),
                      auth=HTTPBasicAuth(self.token, ''))
     if r.status_code == requests.codes.ok:
         return r.json()['messages']
Exemple #22
0
 def make_delete_request(self, url, uuid):
     "Example of calling the API using the API Key to delete data from an endpoint"
     auth = HTTPBasicAuth(self.api_auth["uuid"], self.api_auth["secret"])
     return requests.delete(url.format(self.host, uuid), auth=auth)
Exemple #23
0
 def get_all_users(self):
     r = requests.get(self.url + 'users',
                      auth=HTTPBasicAuth(self.token, ''))
     if r.status_code == requests.codes.ok:
         return r.json()['users']
     return False
Exemple #24
0
# coding: UTF-8 NO BOM

import requests
from requests.auth import HTTPBasicAuth

url_post_base = 'http://localhost/mysite/wp-json/wp/v2/posts'

####GET posts######
ret_get = requests.get(url_post_base, auth=HTTPBasicAuth('elev', 'elev'))
print(ret_get.content)
print(ret_get.status_code)
###########################
Exemple #25
0
 def get_user_id(self, username):
     r = requests.get(self.url + 'users/' + username,
                      auth=HTTPBasicAuth(self.token, ''))
     if r.status_code == requests.codes.ok:
         return r.json()['id']
     return False
Exemple #26
0
import json

import requests
from requests.auth import HTTPBasicAuth

api_host = 'http://*****:*****@example.com',
    'name': 'John Doe',
    'surname': 'Doe',
    'tenant': tenant_uri,
    'userServer': '/api/v1/servers/36443f113ac44150aa3732f28e6bf565/',
    'username': '******',
}

data = json.dumps(user)
headers = {
    'accept': 'application/json',
    'content-type': 'application/json',
}

response = requests.post(url=url,
                         headers=headers,
                         data=data,
                         auth=HTTPBasicAuth('admin@origin', 'a'))
created_user = json.loads(response.text)
Exemple #27
0
        break

print("Success: {}  Error: {}".format(success_count, error_count))

# https://stackoverflow.com/questions/18139093/base64-authentication-python

api_URL = "http://192.168.1.109/cgi-bin/snapshot.cgi"
usrPass = '******'
b64Val = base64.b64encode(usrPass)
r = requests.post(
    api_URL,
    headers={"Authorization": "Basic %s" % b64Val},
)

from requests.auth import HTTPBasicAuth
r = requests.post(api_URL, auth=HTTPBasicAuth('admin',
                                              'uwasat0ad'))  #, data=payload)
r.request.headers['Authorization']

for i in range(100):

    try:
        response = camera.snapshot(0)
        print(i, "success")
        img_bytes = response.read()
        img_array = Image.open(io.BytesIO(img_bytes))
        img_numpy = numpy.array(img_array)
        cv2.imshow('Amcrest', img_numpy)
    except:
        print(i, "error")

    # time.sleep(1)
Exemple #28
0
def create_page(options, issue_key, summary):
    """
    Creates a new Confluence page and links it with a JIRA ticket
    """
    parent_page_id = options.parent_page_id(issue_key)
    if parent_page_id <= 0:
        return {'result': 'Not a supported space'}

    data = {
        'ancestors': [{
            'id': parent_page_id
        }],
        'body': {
            'storage': {
                "value": """
                <ac:structured-macro ac:name=\"details\" ac:schema-version=\"1\" ac:macro-id=\"6e9b2ec2-f34c-4130-bf49-de9eb13d3225\">
                    <ac:parameter ac:name=\"label\" />
                    <ac:rich-text-body>
                        <table class=\"wrapped\">
                            <tbody>
                                <tr>
                                    <th>Status</th>
                                    <td>
                                        <ac:structured-macro ac:name=\"status\" ac:schema-version=\"1\" ac:macro-id=\"ab9a9bc7-e671-476b-889c-0c553ca825cb\">
                                            <ac:parameter ac:name=\"colour\">Grey</ac:parameter>
                                            <ac:parameter ac:name=\"title\">Not started</ac:parameter>
                                        </ac:structured-macro>
                                    </td>
                                </tr>
                                <tr>
                                    <th>Stakeholders</th>
                                    <td>
                                        <ac:placeholder>(insert stakeholder here)</ac:placeholder>
                                    </td>
                                </tr>
                                <tr>
                                    <th>Outcome</th>
                                    <td>
                                        <ac:placeholder>What did you decide?</ac:placeholder>
                                    </td>
                                </tr>
                                <tr>
                                    <th>Due date</th>
                                    <td>
                                        <ac:placeholder>When is the due date?</ac:placeholder>
                                    </td>
                                </tr>
                                <tr>
                                    <th>Owner</th>
                                    <td>
                                        <ac:placeholder>(insert owner here)</ac:placeholder>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </ac:rich-text-body>
                </ac:structured-macro>

                <h2>Overview</h2>
                <p>Decide on something</p>

                <h2>Decision</h2>
                <ac:structured-macro ac:name=\"tip\" ac:schema-version=\"1\" ac:macro-id=\"01fe8df3-1f03-4706-b117-cdc1b32f8b08\">
                    <ac:rich-text-body>
                        <p>Decision</p>
                    </ac:rich-text-body>
                </ac:structured-macro>

                """,
                "representation": "storage",
            }
        },
        'space': {
            'key': extract_space_key(issue_key)
        },
        'status': 'current',
        'title': summary,
        'type': 'page'
    }

    auth = HTTPBasicAuth(options.username, options.password)
    base_url = options.base_url

    # create page
    print('Creating page')
    result = requests.post(
        f'https://{base_url}.atlassian.net/wiki/rest/api/content',
        auth=auth,
        headers={
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        json=data)
    result.raise_for_status()
    create_page_response = result.json()
    new_page_id = create_page_response['id']
    print(f'Page created {new_page_id}')

    # add label 'decisions'
    print('Marking page with label decision')
    result = requests.post(
        f'https://{base_url}.atlassian.net/wiki/rest/api/content/{new_page_id}/label',
        auth=auth,
        headers={
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        json=[{
            'name': 'decisions'
        }])
    result.raise_for_status()

    # create link from jira to confluence page
    print('Linking from jira to confluence')
    result = requests.post(
        f'https://{base_url}.atlassian.net/rest/api/2/issue/{issue_key}/remotelink',
        auth=auth,
        headers={
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        json={
            "globalId":
            f"appId=cf551dd2-cf83-37ca-a19c-62fffd328e08&pageId={new_page_id}",
            "application": {
                "type": "com.atlassian.confluence",
                "name": "System Confluence"
            },
            "relationship": "Wiki Page",
            "object": {
                "url": view_page_url(base_url, new_page_id),
                "title": "Wiki Page"
            }
        })
    result.raise_for_status()
    return create_page_response
Exemple #29
0
 def _configure_auth(self, username=None, password=None):
     """Configure the http object to use basic auth headers."""
     http = requests.sessions.Session()
     if username is not None and password is not None:
         http.auth = HTTPBasicAuth(username, password)
     return http
Exemple #30
0
 def get_json_auth(url):
     auth = HTTPBasicAuth(GITHUB_USERNAME, GITHUB_PASSWORD)
     req = requests.get(url, auth=auth)
     return req.json()
    r = s.get(f"""{http}/hs/gate/v1?method=init_call&data={value}""", headers=headers, auth=auth_ones)

    if r.status_code == 200:
        r = s.get(f"""{http_socket}/users/ringing?data={r.text}""")
    else:
        logging.info(str(r.reason)+' -> '+str(r.text))
    

ami_ip = "192.168.180.253"
ami_port = 5038
ami_user = '******'
ami_secret='amipassword'

headers = {'Content-type': 'application/json'}
http = 'http://192.168.180.150/umc'
auth_ones = HTTPBasicAuth('4', 'R')

http_socket = "http://192.168.180.150:8099"

s = requests.Session()

client = AMIClient(address=ami_ip, port=ami_port)

AutoReconnect(client)

try:
    future = client.login(username=ami_user, secret=ami_secret)
except:
    raise Exception('ami client login failed')

time.sleep(0.5)
# The first step is to create a SOAP client session
session = Session()

# We avoid certificate verification by default
# And disable insecure request warnings to keep the output clear
session.verify = False
urllib3.disable_warnings( urllib3.exceptions.InsecureRequestWarning )

# To enable SSL cert checking (recommended for production)
# place the CUCM Tomcat cert .pem file in the root of the project
# and uncomment the two lines below

# CERT = 'changeme.pem'
# session.verify = CERT

session.auth = HTTPBasicAuth( os.getenv( 'USERNAME' ), os.getenv( 'PASSWORD' ) )

transport = Transport( session = session, timeout = 10 )

# strict=False is not always necessary, but it allows Zeep to parse imperfect XML
settings = Settings( strict = False, xml_huge_tree = True )

# If debug output is requested, add the MyLoggingPlugin callback
plugin = [ MyLoggingPlugin() ] if DEBUG else []

# Create the Zeep client with the specified settings
client = Client( WSDL_FILE, settings = settings, transport = transport,
        plugins = plugin )

# Create the Zeep service binding to AXL at the specified CUCM
service = client.create_service( '{http://www.cisco.com/AXLAPIService/}AXLAPIBinding',
requests.packages.urllib3.disable_warnings()  # Disable warnings

# DNAC IP, modify these parameters if you are using your own DNAC
#dnac_ip = "sandboxdnac.cisco.com"
#username = "******"
#password = "******"
#version = "v1"

# POST token API URL
#post_url = "https://" + dnac_ip + "/api/system/" + version + "/auth/token"
post_url = "https://" + dnac_config.DNAC_IP + "/api/system/" + dnac_config.VERSION + "/auth/token"

# All DNAC REST API request and response content type is JSON.
headers = {'content-type': 'application/json'}

# Make request and get response - "resp" is the response of this request
resp = requests.post(post_url,
                     auth=HTTPBasicAuth(username=dnac_config.USERNAME,
                                        password=dnac_config.PASSWORD),
                     headers=headers,
                     verify=False)
print("Request Status: ", resp.status_code)

# Get the json-encoded content from response
response_json = resp.json()
print("\nRaw response from POST token request:\n", resp.text)
# Not that easy to read the raw response, so try the formatted print out

# Pretty print the raw response
print("\nPretty print response:\n", json.dumps(response_json, indent=4))