Python connection got error "urllib2.HTTPError: HTTP Error 401: Unauthorized"

(Romolo Almeida) #1

Hi all,

Im trying to access “…:8080/_status/nodes”, in a insecure install everything is ok, but when run at secure installation of cockroachdb, whenever send a correct pass, always got “Error 401: Unauthorized”

Everyone has a working python code to connect to this url using ssl and auth?

Below more details.

Regards,
Romolo.

------- python code -------
import urllib2
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
url = ‘https://localhost:8080/_status/nodes
password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
password_mgr.add_password(None, url, ‘mon’,‘mon’)
auth_handler = urllib2.HTTPBasicAuthHandler(password_mgr)
request = urllib2.Request( url , [auth_handler] )
request.add_header(‘User-Agent’, “Mozilla/5.0”)
request.add_header(‘Accept’, “/”)
request.add_header(‘Cache-Control’, “no-cache”)
request.add_header(‘accept-encoding’, “gzip, deflate”)
request.add_header(‘Connection’, “keep-alive”)
request.add_header(‘cache-control’, “no-cache”)
response = urllib2.urlopen(url)

----- error that I got -----
$> python mycode.py
Traceback (most recent call last):
File “cockroachdb_ssl_forum.py”, line 20, in
response = urllib2.urlopen(url)
File “/usr/lib/python2.7/urllib2.py”, line 154, in urlopen
return opener.open(url, data, timeout)
File “/usr/lib/python2.7/urllib2.py”, line 435, in open
response = meth(req, response)
File “/usr/lib/python2.7/urllib2.py”, line 548, in http_response
‘http’, request, response, code, msg, hdrs)
File “/usr/lib/python2.7/urllib2.py”, line 473, in error
return self._call_chain(*args)
File “/usr/lib/python2.7/urllib2.py”, line 407, in _call_chain
result = func(*args)
File “/usr/lib/python2.7/urllib2.py”, line 556, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 401: Unauthorized

(Ron Arévalo) #2

Hey @romolo_almeida,

I’m not super familiar with urllib, but here is some code that would work using the requests lib:

import requests
import json

payload = {'username': "YOUR USERNAME",
			'password': "YOUR PASSWORD"}


# Use 'with' to ensure the session context is closed after use.
with requests.Session() as s:
	#CONVERT THE DICT TO JSON FOR THE DATA PAYLOAD
	data_to_send = json.dumps(payload).encode("utf-8")
	login = s.post('https://localhost:8080/login', data=data_to_send, verify='certs/ca.crt')

	#AN AUTHORIZED REQUEST
	r = s.get('https://localhost:8080/_status/nodes', cert=('certs/client.root.crt', 'certs/client.root.key'))
	#DATA CAN BE R.JSON(), OR R.TEXT, OR R.CONTENT
	data = r.json()

	print(data)

Let me know if you have any questions.

Thanks,

Ron

(Romolo Almeida) #3

Hi Ron,

Thankyou by your response, but “requests” module is available only on python 3+ and I’m using 2.7 (https://docs.python.org/release/2.7/modindex.html).

You know another method using module “urllib2” on replace for “requests” ?

Regards,

Romolo.

(Ron Arévalo) #4

Hey @romolo_almeida,

You should be able to use Requests with Python 2.7.

This is from the Requests website:

Requests officially supports Python 2.7 & 3.4–3.7, and runs great on PyPy.

So you should be able to run it on your app without any issues, however, if you need to use urllib2 I would suggest combing through their docs to see if there’s a way to keep an open session, but from a quick glance at them, I didn’t see anything that stood out, but as I mentioned, I’m not very familiar with this library.

Thanks,

Ron