I am able to access a webservice by using curl as given below
curl -k -u "admin:password" "https://10.184.39.12:8080/mypage/managed/user?_query=query-all"
I want to access it by python code. I can use httplib.
connection.request("GET",url,params,headers)
Are the options -k, -u "admin:password" are headers.
If so how could I write in code as headers?
Please help.
You need to encode your username and password as base64 and add that to the headers. Something like this:
import base64
import string
import httplib
auth = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
webservice = httplib.HTTP(host)
webservice.putheader("Authorization", "Basic %s" % auth)
# Add other headers etc
There's more information on this blog post: http://mozgovipc.blogspot.nl/2012/06/python-http-basic-authentication-with.html
Related
I am trying write a python script using requests package to use an online mongodb query service API hosted within the organization. The API expects the authorization header in the format 'websitename/username:Password' and using the basic authentication base64 encoding. I tried to create the GET request using the requests package which has the authorization header in the following format:
import requests
headers = {'Authorization': 'Basic %s' % 'Base64encoded
websitename/username:Password string here'}
content_res = requests.get(get_url, headers = headers).json()
But I am getting a parse error here for the string as I think the expected string for header in requests package is in form of 'username:password' here and not the desired format i.e. 'websitename/username:password'.
Is there a way in which I could use the base64 encoded sting in the format which the service is expecting i.e. 'websitename/username:password' in requests package?
Any help is highly appreciated.
Thanks.
It sounds to me like you are getting a HTTP response error because the authorization header value you are passing is not base64 encoded. To correct this you can simply encode the string using the base64 python module:
Python 2.7 https://docs.python.org/2/library/base64.html
Python 3.5 https://docs.python.org/3.5/library/base64.html
An example would be something like this:
import base64
import requests
website = 'example.com'
username = 'root'
password = '1234'
auth_str = '%s/%s:%s' % (website, username, password)
b64_auth_str = base64.b64encode(auth_str)
headers = {'Authorization': 'Basic %s' % b64_auth_str}
content_res = requests.get(get_url, headers=headers).json()
import base64
import requests
website = 'example.com'
username = 'root'
password = '1234'
auth_str = '%s/%s:%s' % (website, username, password)
b64_auth_str = base64.b64encode(auth_str.encode('ascii'))
headers = {'Authorization': 'Basic %s' % b64_auth_str}
content_res = requests.get(get_url, headers=headers).json()
I tried to call AppDynamics API using python requests but face an issue.
I wrote a sample code using the python client as follows...
from appd.request import AppDynamicsClient
c = AppDynamicsClient('URL','group','appd#123')
for app in c.get_applications():
print app.id, app.name
It works fine.
But if I do a simple call like the following
import requests
usr =<uid>
pwd =<pwd>
url ='http://10.201.51.40:8090/controller/rest/applications?output=JSON'
response = requests.get(url,auth=(usr,pwd))
print 'response',response
I get the following response:
response <Response [401]>
Am I doing anything wrong here ?
Couple of things:
I think the general URL format for app dynamics applications are (notice the '#'):
url ='http://10.201.51.40:8090/controller/#/rest/applications?output=JSON'
Also, I think the requests.get method needs an additional parameter for the 'account'. For instance, my auth format looks like:
auth = (_username + '#' + _account, _password)
I am able to get a right response code back with this config. Let me know if this works for you.
You could also use native python code for more control:
example:
import os
import sys
import urllib2
import base64
# if you have a proxy else comment out this line
proxy = urllib2.ProxyHandler({'https': 'proxy:port'})
opener = urllib2.build_opener(proxy)
urllib2.install_opener(opener)
username = "YOUR APPD REST API USER NAME"
password = "YOUR APPD REST API PASSWORD"
#Enter your request
request = urllib2.Request("https://yourappdendpoint/controller/rest/applications/141/events?time-range-type=BEFORE_NOW&duration-in-mins=5&event-types=ERROR,APPLICATION_ERROR,DIAGNOSTIC_SESSION&severities=ERROR")
base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
request.add_header("Authorization", "Basic %s" % base64string)
response = urllib2.urlopen(request)
html = response.read()
This will get you the response and you can parse the XML as needed.
If you prefer it in JSON simply specify it in the request.
I'm trying to get the following curl command to work in Python 2.7:
curl --header "Accept: application/vnd.github.korra-preview" --user [username]:[password] https://api.github.com/orgs/myorg/outside_collaborators?per_page=100\&page=1
(basically just gets a list of collaborators from a GitHub organization)
This is utilising the GitHub API v3 - https://developer.github.com/v3/orgs/outside_collaborators/
I've read through the Requests library documentation and can't figure out how to pass BOTH authorisation and custom headers. Does anyone know how to do this?
This is the code I've written so far. How do I include both the auth and varHeaders in the get request?
import requests
varUsername = raw_input("GitHub username:\n")
varPassword = raw_input("GitHub password:\n")
varHeaders = {'Accept':'application/vnd.github.korra-preview'}
#req = requests.get('https://api.github.com/user/repos',auth=(varUsername,varPassword))
req = requests.get('https://api.github.com/orgs/myorg/outside_collaborators?per_page=100\&page=1',auth=(varUsername,varPassword))
print req.status_code
print req.headers
print req.encoding
print req.text
print req.json()
You can add a third parameter, in the form 'headers=varHeaders'
req = requests.get('https://api.github.com/orgs/myorg/outside_collaborators?per_page=100\&page=1',auth=(varUsername,varPassword),headers=varHeaders)
Thanks Brendan for pointing this out!
I am trying to port the following curl call into a python script using urllib/urllib2 :
curl -H "X-Api-Key: ccccccccccccccccccccccc" -H "X-Api-Secret: cbcwerwerwerwerwerwerweweewr9" https://api.assembla.com/v1/users/user.xml
I tried using the standard url call, but it failed:
url_assembla = 'https://api.assembla.com/v1/users/suer.xml'
base64string_assembla = base64.encodestring('%s:%s' % ('ccccccccccccccccccccccc','cbcwerwerwerwerwerwerweweewr9')).replace('\n', '')
req_assembla = urllib2.Request(url_assembla)
req_assembla.add_header("Authorization", "Basic %s" % base64string_assembla)
ET.parse(urllib2.urlopen(req_assembla))
Can any one advice on how to incorporate the Api-secret and Api-key. I want to do this as a script, so did not want to install the assembla package.
Thanks
If the curl command above works, you should perhaps just add the same headers into the urllib2 query?
Try this instead of the add_header("Authorization") line:
req_assembla.add_header("X-Api-Key", 'ccccccccccccccccccccccc')
req_assembla.add_header("X-Api-Secret", 'cbcwerwerwerwerwerwerweweewr9')
The following curl command works perfectly (private data anonymized):
curl -X POST 'https://api.twilio.com/2010-04-01/Accounts/abc/SMS/Messages.json' \
-d 'From=%2B14155551234' \
-d 'To=%2B17035551212' \
-d 'Body=This+is+a+test' \
-u foo:bar
How can I send out this exact same HTTPS POST request in the proper Python3.3 way? I don't want to have to use anything other than Python 3.3's standard library if I can avoid it (in other words, not using the twilio python module, or "requests", or pycurl, or anything outside the plain vanilla Python 3.3 installation).
The preferred Python approach seems to keep evolving from version to version, the snippets I find by Googling never mention which version they're using or don't do the login part, the Python docs are full of "deprecated since 3.x" but never include code examples of the new way to do things....
If curl can do this so easily, so can standard Python 3.3. But how exactly is this supposed to be done now?
Here's a version that works both on Python 2 and 3:
import requests # pip install requests
url = 'https://api.twilio.com/2010-04-01/Accounts/abc/SMS/Messages.json'
r = requests.post(url, dict(
From='+17035551212',
To='+17035551212',
Body='This is a test'), auth=('foo', 'bar'))
print(r.headers)
print(r.text) # or r.json()
To make https post request with basic http authentication on Python 3.3:
from base64 import b64encode
from urllib.parse import urlencode
from urllib.request import Request, urlopen
user, password = 'foo', 'bar'
url = 'https://api.twilio.com/2010-04-01/Accounts/abc/SMS/Messages.json'
data = urlencode(dict(From='+17035551212', To='+17035551212',
Body='This is a test')).encode('ascii')
headers = {'Authorization': b'Basic ' +
b64encode((user + ':' + password).encode('utf-8'))}
cafile = 'cacert.pem' # http://curl.haxx.se/ca/cacert.pem
response = urlopen(Request(url, data, headers), cafile=cafile)
print(response.info())
print(response.read().decode()) # assume utf-8 (likely for application/json)