def get_auth_handler(cls, feed_url, username, password, logger=None): """ Create a URL that will perform authentication for the given feed. Arguments: feed_url -- The URL of the feed to retrieve (as a string) username -- The username to use when authenticating password -- The password to use when authenticating """ realm, auth_type = cls.get_realm_and_auth_type(feed_url, username, password, logger) # Make the associated auth handler if auth_type == None: return None elif auth_type.lower() == "basic": auth_handler = HTTPBasicAuthHandler() else: auth_handler = HTTPDigestAuthHandler() # Set the password auth_handler.add_password(realm=realm, uri=feed_url, user=username, passwd=password) return auth_handler
def unavco_dl(d, opt_dict): user_name = password_config.unavuser user_password = password_config.unavpass url = d['downloadUrl'] passman = HTTPPasswordMgrWithDefaultRealm() passman.add_password(None, 'https://imaging.unavco.org/data/sar/lts', user_name, user_password) authhandler = HTTPDigestAuthHandler(passman) opener = build_opener(authhandler) filename = os.path.basename(url) try: f = opener.open(url) except HTTPError as e: print(e) return dl_file_size = int(f.info()['Content-Length']) if os.path.exists(filename): file_size = os.path.getsize(filename) if dl_file_size == file_size: print("%s already downloaded" % filename) f.close() return start = time.time() CHUNK = 256 * 10240 with open(filename, 'wb') as fp: while True: chunk = f.read(CHUNK) if not chunk: break fp.write(chunk) total_time = time.time() - start mb_sec = (os.path.getsize(filename) / (1024 * 1024.0)) / total_time print("%s download time: %.2f secs (%.2f MB/sec)" % (filename, total_time, mb_sec)) f.close()
def set_authentication(self, uri, login, password): password_manager = HTTPPasswordMgrWithDefaultRealm() password_manager.add_password(realm=None, uri=uri, user=login, passwd=password) self.http_opener = build_opener( HTTPBasicAuthHandler(password_manager), HTTPDigestAuthHandler(password_manager))
def open(request): request = request_vim_to_python(request) rhandler = HTTPRedirectHandler() rhandler.max_redirections = request['max_redirect'] opener = build_opener(rhandler) if request['username']: passmgr = HTTPPasswordMgrWithDefaultRealm() passmgr.add_password( None, request['url'], request['username'], request['password'], ) opener.add_handler(HTTPBasicAuthHandler(passmgr)) opener.add_handler(HTTPDigestAuthHandler(passmgr)) req = Request( url=request['url'], data=request['data'], headers=request['headers'], method=request['method'], ) if request['gzip_decompress']: req.add_header('Accept-encoding', 'gzip') try: res = retry(tries=request['retry'])(opener.open)( req, timeout=request['timeout']) except HTTPError as e: res = e if not hasattr(res, 'version'): # urllib2 does not have 'version' field import httplib res.version = httplib.HTTPConnection._http_vsn response_status = "HTTP/%s %d %s\n" % ( '1.1' if res.version == 11 else '1.0', res.code, res.msg, ) response_headers = str(res.headers) response_body = res.read() if (request['gzip_decompress'] and res.headers.get('Content-Encoding') == 'gzip'): response_body = gzip_decompress(response_body) if hasattr(res.headers, 'get_content_charset'): # Python 3 response_encoding = res.headers.get_content_charset() else: # Python 2 response_encoding = res.headers.getparam('charset') response_body = response_body.decode(response_encoding) return ( request['url'], response_status + response_headers, response_body, )
def __init__(self, device_data): """Set up how we are going to connect to the ICS Calendar""" self.name = device_data[CONF_NAME] self.url = device_data[CONF_URL] self.include_all_day = device_data[CONF_INCLUDE_ALL_DAY] self.event = None if device_data[CONF_USERNAME] != '' \ and device_data[CONF_PASSWORD] != '': passman = HTTPPasswordMgrWithDefaultRealm() passman.add_password(None, self.url, device_data[CONF_USERNAME], device_data[CONF_PASSWORD]) basicAuthHandler = HTTPBasicAuthHandler(passman) digestAuthHandler = HTTPDigestAuthHandler(passman) opener = build_opener(digestAuthHandler, basicAuthHandler) install_opener(opener)
def __init__(self, base_url, user=None, password=None, log_function=None): """ Args: base_url (str): the URL displayed in the Sweech app (ex: 'http://192.168.0.65:4444') user (str, optional): the username if login is enabled in the app password (str, optional): the password if login is enabled in the app log_function (function): a function to be called to log runtime information """ self.base_url = base_url self._log_function = log_function passwordmgr = HTTPPasswordMgrWithDefaultRealm() passwordmgr.add_password('Sweech', base_url, user, password) auth_handler = HTTPDigestAuthHandler(passwordmgr) https_auth_handler = HTTPSDigestAuthHandler( passwordmgr, ssl.SSLContext(ssl.PROTOCOL_SSLv23)) self._opener = build_opener(auth_handler, https_auth_handler)
def get_opener(url, user, password): '''Returns an opener to be used for downloading data with a given user and password. All arguments should be strings. :param url: the domain name of the given url :param: string, the user name :param password: the password :return: an urllib opener ''' parsed_url = urlparse(url) base_url = "%s://%s" % (parsed_url.scheme, parsed_url.netloc) handlers = [] password_mgr = HTTPPasswordMgrWithDefaultRealm() password_mgr.add_password(None, base_url, user, password) handlers.append(HTTPDigestAuthHandler(password_mgr)) return build_opener(*handlers)
def set_user_name_password(self, user_name: str, password: str): """Set a user name and password to use. The user name and password will be set into an HTTPBasicAuthHandler an an HTTPDigestAuthHandler. Both are attached to a new urlopener, so that HTTP Basic Auth and HTTP Digest Auth will be supported when opening the URL. :param user_name: The user name :type user_name: str :param password: The password :type password: str """ passman = HTTPPasswordMgrWithDefaultRealm() passman.add_password(None, self.url, user_name, password) basic_auth_handler = HTTPBasicAuthHandler(passman) digest_auth_handler = HTTPDigestAuthHandler(passman) opener = build_opener(digest_auth_handler, basic_auth_handler) install_opener(opener)
def __init__(self, url): self.handlers = [] self.parsed_url = url = urlparse(url) self.scheme = url.scheme self.insecure = False if url.scheme == 'https+insecure': self.insecure = True url = url._replace(scheme='https') if url.port: self.netloc = '{0.hostname}:{0.port}'.format(url) else: self.netloc = url.hostname cleaned_url = urlunparse(url._replace(netloc=self.netloc)) if url.username or url.password: password_mgr = HTTPPasswordMgrWithDefaultRealm() password_mgr.add_password(None, cleaned_url, url.username, url.password) self.handlers.append(HTTPDigestAuthHandler(passwd=password_mgr)) self.handlers.append(HTTPBasicAuthHandler(password_mgr=password_mgr)) self.url = cleaned_url
def __init__(self, url=None, passfile=None, realm=None, debug=False): self._realm = realm self._debug = debug # # Cookies are necessary to maintain connection during script. # # Taken from: # http://www.voidspace.org.uk/python/articles/cookielib.shtml # cj = LWPCookieJar() self.opener = build_opener(HTTPCookieProcessor(cj)) # install_opener(opener) # # Handle login # if url is None: raise ValueError("A Trac URL is required!") self.url = url foo = self.url.split('/') self._baseurl = foo[0] + '//' + foo[2] if passfile is None: user, password = self._readPasswordNetrc(self._baseurl) else: user, password = self._readPassword(passfile) if password is None: raise ValueError(('Could not find a password for ' + '{0}!').format(self.url)) parser = SimpleWikiHTMLParser() if self._realm is not None: auth_handler = HTTPDigestAuthHandler() auth_handler.add_password(realm=self._realm, uri=self.url, user=user, passwd=password) self.opener.add_handler(auth_handler) response = self.opener.open(self.url + "/login") if self._debug: print(response.getcode()) print(response.info()) parser.feed(response.read().decode('utf-8')) response.close() self._form_token = parser.search_value if self._realm is None: postdata = {'user': user, 'password': password, '__FORM_TOKEN': self._form_token, 'referer': ''} # # The cookie named 'trac_auth' is obtained after the POST to the # login page but before the redirect to the wiki front page. # Technically it is obtained in the HTTP headers of the redirect. # response = self.opener.open(self.url+"/login", urlencode(postdata).encode('utf-8')) if self._debug: print(response.getcode()) print(response.info()) response.close() self._cookies = list() for cookie in cj: if self._debug: print(cookie) self._cookies.append((cookie.name, cookie.value)) if cookie.name == 'trac_form_token' and self._form_token is None: self._form_token = cookie.value return
def __init__(self, cameras, zoom=None): grid_coords = [[(320, 180, 640, 360)], [(0, 180, 640, 360), (640, 180, 640, 360)], [(0, 0, 640, 360), (640, 0, 640, 360), (180, 360, 640, 360)], [(0, 0, 640, 360), (640, 0, 640, 360), (0, 360, 640, 360), (640, 360, 640, 360)], [(0, 120, 427, 240), (427, 120, 427, 240), (854, 120, 427, 240), (214, 360, 427, 240), (640, 360, 427, 240)], [(0, 120, 427, 240), (427, 120, 427, 240), (854, 120, 427, 240), (0, 360, 427, 240), (427, 360, 427, 240), (854, 360, 427, 240)], [(0, 0, 427, 240), (427, 0, 427, 240), (854, 0, 427, 240), (214, 240, 427, 240), (640, 240, 427, 240), (214, 480, 427, 240), (640, 480, 427, 240)], [(0, 0, 427, 240), (427, 0, 427, 240), (854, 0, 427, 240), (0, 240, 427, 240), (427, 240, 427, 240), (854, 240, 427, 240), (214, 480, 427, 240), (640, 480, 427, 240)], [(0, 0, 427, 240), (427, 0, 427, 240), (854, 0, 427, 240), (0, 240, 427, 240), (427, 240, 427, 240), (854, 4800, 427, 240), (0, 480, 427, 240), (427, 480, 427, 240), (854, 480, 427, 240)]] posX = 5 posY = 5 lblWidth = 80 lblHeight = 80 lblFont = 'font_clock' lblColor = '0xFFFFFFFF' self.threads = [] self.zoom = zoom self.select = None if self.zoom: self.cams = [cameras[self.zoom - 1].copy()] else: self.cams = cameras self.total = len(cameras) self.count = len(self.cams) passwd_mgr = HTTPPasswordMgrWithDefaultRealm() self.opener = build_opener() self.addControl(xbmcgui.ControlImage(0, 0, 1280, 720, __black__)) for i in range(self.count): if self.cams[i]['username'] and self.cams[i]['password']: passwd_mgr.add_password(None, self.cams[i]['url'], self.cams[i]['username'], self.cams[i]['password']) self.opener.add_handler(HTTPBasicAuthHandler(passwd_mgr)) self.opener.add_handler(HTTPDigestAuthHandler(passwd_mgr)) randomname = ''.join([ random.choice(string.ascii_letters + string.digits) for n in range(32) ]) self.cams[i]['tmpdir'] = os.path.join(__profile__, randomname) if not xbmcvfs.exists(self.cams[i]['tmpdir']): xbmcvfs.mkdir(self.cams[i]['tmpdir']) if self.zoom: self.cams[i]['x'], self.cams[i]['y'], self.cams[i][ 'width'], self.cams[i]['height'] = 0, 0, 1280, 720 elif not SETTINGS['customGrid']: self.cams[i]['x'], self.cams[i]['y'], self.cams[i][ 'width'], self.cams[i]['height'] = grid_coords[self.count - 1][i] self.cams[i]['control'] = xbmcgui.ControlImage( self.cams[i]['x'], self.cams[i]['y'], self.cams[i]['width'], self.cams[i]['height'], __black__, aspectRatio=self.cams[i]['aspectRatio']) self.addControl(self.cams[i]['control']) if self.zoom: self.addControl( xbmcgui.ControlLabel(posX, posY, lblWidth, lblHeight, str(self.zoom), alignment=6, font=lblFont, textColor=lblColor))