@cryptotaxi247 / netdata-1 / commits / 2d70fb35c

HTTP basic auth

paulfantom committed Jul 5, 2016 at 00:48 UTC 2d70fb35c6cda993c92b714dabaf1dcfe2cb256e
1 file changed +29 -9
python.d/python_modules/base.py
+29 -9
@@ -7,9 +7,11 @@ import sys
7 import os
8 import socket
9 try:
10 - from urllib.request import urlopen
10 + # from urllib.request import urlopen, Request, HTTPPasswordMgrWithDefaultRealm
11 + import urllib.request as urllib2
12 except ImportError:
12 - from urllib2 import urlopen
13 + # from urllib2 import urlopen, Request, HTTPPasswordMgrWithDefaultRealm
14 + import urllib2
15
16 # from subprocess import STDOUT, PIPE, Popen
17 import threading
@@ -366,14 +368,19 @@ class SimpleService(BaseService):
368
369
370 class UrlService(SimpleService):
369 - # TODO HTTP Basic Authentication
371 def __init__(self, configuration=None, name=None):
372 self.url = ""
373 self.user = None
374 self.password = None
374 - self.request = None
375 SimpleService.__init__(self, configuration=configuration, name=name)
376
377 + def __add_auth(self):
378 + passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
379 + passman.add_password(None, self.url, self.user, self.password)
380 + authhandler = urllib2.HTTPBasicAuthHandler(passman)
381 + opener = urllib2.build_opener(authhandler)
382 + urllib2.install_opener(opener)
383 +
384 def _get_raw_data(self):
385 """
386 Get raw data from http request
@@ -381,15 +388,17 @@ class UrlService(SimpleService):
388 """
389 raw = None
390 try:
384 - f = urlopen(self.url, timeout=self.update_every)
391 + f = urllib2.urlopen(self.url, timeout=self.update_every)
392 + except Exception as e:
393 + msg.error(self.__module__, str(e))
394 + return None
395 +
396 + try:
397 raw = f.read().decode('utf-8')
398 except Exception as e:
399 msg.error(self.__module__, str(e))
400 finally:
389 - try:
390 - f.close()
391 - except:
392 - pass
401 + f.close()
402 return raw
403
404 def check(self):
@@ -405,6 +414,17 @@ class UrlService(SimpleService):
414 self.url = str(self.configuration['url'])
415 except (KeyError, TypeError):
416 pass
417 + try:
418 + self.user = str(self.configuration['user'])
419 + except (KeyError, TypeError):
420 + pass
421 + try:
422 + self.password = str(self.configuration['password'])
423 + except (KeyError, TypeError):
424 + pass
425 +
426 + if self.user is not None and self.password is not None:
427 + self.__add_auth()
428
429 if self._get_data() is not None:
430 return True