def __init__(self, ctx: PipelineContext, config: ModeConfig): super().__init__(ctx) self.config = config self.report = SourceReport() self.session = requests.session() self.session.auth = HTTPBasicAuth(self.config.token, self.config.password) self.session.headers.update({ "Content-Type": "application/json", "Accept": "application/hal+json", }) # Test the connection try: self._get_request_json(f"{self.config.connect_uri}/api/account") except HTTPError as http_error: self.report.report_failure( key="mode-session", reason=f"Unable to retrieve user " f"{self.config.token} information, " f"{str(http_error)}", ) self.workspace_uri = f"{self.config.connect_uri}/api/{self.config.workspace}" self.space_tokens = self._get_space_name_and_tokens()
def __init__(self, username: str, password: str = None, api_token: str = None, api_token_file: str = None): # user gave password directly, just use it if password: pass # use the api token just like a password elif api_token: password = api_token # read the first line in the file and use like an api token elif api_token_file: with open(api_token_file, 'r') as f: password = f.readline().strip() # nothing was given to us, raise else: raise Exception("Not authentication provided") # auth used self.auth = HTTPBasicAuth(username=username, password=password) # hold the session so our crumbs don't reset self.session: requests.Session = requests.Session() # data from crumbapi self.crumb: str = None self.crumb_request_field: str = None
def fetch_free_busy(date, tz, uid, email): ox_url = current_app.config['OX_PROVIDER_URL'] ox_username = current_app.config['OX_PROVIDER_USERNAME'] ox_password = current_app.config['OX_PROVIDER_PASSWORD'] ox_context_id = current_app.config['OX_PROVIDER_CONTEXT_ID'] ox_max_weeks = current_app.config.get('OX_PROVIDER_MAX_WEEKS', 4) if not ox_url or not ox_username or not ox_password or not ox_context_id: raise RuntimeError('OX provider not configured!') user_name, server = email.split('@') # see how far into the future we have to fetch data weeks_to_fetch = math.ceil((date - datetime.now().date()).days / 7) or 1 # OX gives free-busy data for exactly the number of weeks, # which cuts off the last day instead of showing data until 23:59. # To get the full day, we request an additional week. # https://github.com/indico/newdle/issues/365 weeks_to_fetch += 1 if weeks_to_fetch > ox_max_weeks: return [] params = { 'contextId': ox_context_id, 'userName': user_name, 'server': server, 'weeksIntoFuture': weeks_to_fetch, } resp = requests.get( ox_url, params=params, auth=HTTPBasicAuth(ox_username, ox_password) ) if not resp.ok: return [] busy_slots = [] for line in resp.text.splitlines(): # this includes BUSY, BUSY-UNAVAILABLE and BUSY-TENTATIVE if line.startswith('FREEBUSY;FBTYPE=BUSY'): try: start_dt, end_dt = [ datetime.strptime(dt, '%Y%m%dT%H%M%S%z') for dt in line.split(':')[1].split('/') ] except IndexError: continue overlap = find_overlap(date, start_dt, end_dt, pytz.timezone(tz)) if overlap: busy_slots.append(overlap) return [ ((start.hour, start.minute), (end.hour, end.minute)) for start, end in busy_slots ]
def __init__(self, host, port, prot, api_key, api_username, api_password, verify): self.url = '{prot}://{host}:{port}/api/v1'.format(prot=prot, host=host, port=port) self.session = requests.Session() if api_key: self.session.headers.update({'X-API-Key': api_key}) elif (api_username and api_password): self.session.auth = HTTPBasicAuth(api_username, api_password) self.session.verify = verify
def update_note(cfg: ConfigParser, note_id: int, title: str, body: str): """Update the note `note_id`""" auth = HTTPBasicAuth(cfg["basic_auth_user"], cfg["basic_auth_password"]) if has_auth_infos(cfg) is True else None response = requests.put(f"{cfg['url']}:{cfg['port']}/api/notes/update/{note_id}", data={"title": title, "content": body}, auth=auth) if response.status_code == 200: print(f"[+] Note {note_id} updated") else: print(f"[!] Error updating note {note_id} : {response}")
def delete_note(cfg: ConfigParser, note_id: int): """Delete the note `note_id`""" auth = HTTPBasicAuth(cfg["basic_auth_user"], cfg["basic_auth_password"]) if has_auth_infos(cfg) is True else None response = requests.delete(f"{cfg['url']}:{cfg['port']}/api/notes/delete/{note_id}", auth=auth) if response.status_code == 200: print(f"[+] Note {note_id} deleted") else: print(f"[!] Error deleting note {note_id} : {response}")
def create_note(cfg: ConfigParser, title: str, body: str): """Create a new note with a title and body""" auth = HTTPBasicAuth(cfg["basic_auth_user"], cfg["basic_auth_password"]) if has_auth_infos(cfg) is True else None response = requests.post(f"{cfg['url']}:{cfg['port']}/api/notes/add", data={"title": title, "content": body}, auth=auth) if response.status_code == 200: print(f"[+] Note created") else: print(f"[!] Error creating note : {response}")
def get_token(controller_url, port, username, password): login_url = "https://{0}:{1}/dna/system/api/v1/auth/token".format( controller_url, port) result = requests.post(login_url, auth=HTTPBasicAuth(username, password), verify=False) result.raise_for_status() token = result.json()["Token"] return {"URL": controller_url, "token": token}
def show_note(cfg: ConfigParser, note_id: int): """Show the note `note_id`""" auth = HTTPBasicAuth(cfg["basic_auth_user"], cfg["basic_auth_password"]) if has_auth_infos(cfg) is True else None response = requests.get(f"{cfg['url']}:{cfg['port']}/api/notes/{note_id}", auth=auth) if response.status_code == 200: tmp = response.json() n = note.Note(tmp["id"], tmp["title"], tmp["content"], tmp["creation_date"], tmp["update_date"]) print(f"{n.title} :\n---") print(f"{n.content}")
def get_access_token(self): """Using stored credentials, gets an access token from the token API.""" url = urllib.parse.urljoin(BASE_URL, ENDPOINTS["token"]) auth = HTTPBasicAuth(self.config["client_id"], self.config["client_secret"]) self.session.fetch_token( token_url=url, client_id=self.config["client_id"], client_secret=self.config["client_secret"], )
def list_notes(cfg: ConfigParser): """List all notes""" auth = HTTPBasicAuth(cfg["basic_auth_user"], cfg["basic_auth_password"]) if has_auth_infos(cfg) is True else None response = requests.get(f"{cfg['url']}:{cfg['port']}/api/notes", auth=auth) if response.status_code == 200: notes: List[Dict] = response.json() print(f"{len(notes)} Note{'' if len(notes) == 1 else 's'} :") for d in notes: n = note.Note(d["id"], d["title"], d["content"], d["creation_date"], d["update_date"]) print(f"\t- {n.title} (id {n.id})")
def store_prices(): prices = { "type": "price", "one_day": 1, "two_days": 2, "three_days": 3, "four_days": 5, "five_days": 6 } requests.post(URL, json=prices, auth=HTTPBasicAuth(USERNAME, PASSWORD)) print('Prices Loaded!!!')
def store_copies(): movies = read_movies() for movie in movies: #TODO: create random number of copies copy = {"type": "copy", "status": "available", "movie": movie} requests.post(cons.URL, json=copy, auth=HTTPBasicAuth(cons.USERNAME, cons.PASSWORD)) requests.post(cons.URL, json=copy, auth=HTTPBasicAuth(cons.USERNAME, cons.PASSWORD)) requests.post(cons.URL, json=copy, auth=HTTPBasicAuth(cons.USERNAME, cons.PASSWORD)) requests.post(cons.URL, json=copy, auth=HTTPBasicAuth(cons.USERNAME, cons.PASSWORD)) requests.post(cons.URL, json=copy, auth=HTTPBasicAuth(cons.USERNAME, cons.PASSWORD)) print('Copies Loaded!!!')
def store_retanls(): clients = read_client() copies = read_copies() for copy in copies: for client in clients: if (choice([0,1]) == 1): rental = { "type": "rental", "client": client, "copy": copy, "date_rental": "08/05/2021", "nro_day": choice([1,2,3,4]), "date_return":"" } requests.post(URL, json=rental, auth=HTTPBasicAuth(USERNAME, PASSWORD)) print('Retanls Loaded!!!')
def run(self): Printer.p(self.NAME, "Checking") if self.check(): Printer.p(self.NAME, "Starting") while not Storage.plugins_queue.empty(): plugin = Storage.plugins_queue.get() url = self.wordpress_url + self.plugins_directory + plugin + "/" Printer.p(self.NAME, "Request to " + url) auth = HTTPBasicAuth(self.basic_auth_user, self.basic_auth_password) self.handle_result( requests.get( url, proxies=self.proxies, auth=(auth if self.basic_auth_user != None else None), verify=False), plugin) time.sleep(self.sleep_between_req_in_milis / 1000.0)
def get_balance(vendor, number): log = PrintingQuotaLog( user=vendor, account=number, type=PrintingQuotaLog.GET, status=PrintingQuotaLog.PENDING, ) log.save() try: request = requests.get( f"https://qpilot.rbg.tum.de:9779/balance/for-card-number/{number}", auth=HTTPBasicAuth(settings.QPILOT_USERNAME, settings.QPILOT_PASSWORD), timeout=5, ) except ConnectTimeout: log.status = PrintingQuotaLog.TIMEOUT log.save() raise TypeError try: request.raise_for_status() except HTTPError as error: if request.status_code == 401: log.status = PrintingQuotaLog.UNAUTHORIZED log.save() raise TypeError if request.status_code == 422: log.status = PrintingQuotaLog.UNKNOWN_NUMBER log.save() raise TypeError raise error log.status = PrintingQuotaLog.SUCCESS log.save() return round(float(request.json()["totalBalance"]), 2)
def bruteforce(): mot_de_pase = "" args = parse_arguments() if verification(): wordlist = open(args.dico, "r").readlines() for line in wordlist: line = line.strip() requete = requests.get(args.target, auth=HTTPBasicAuth(args.username, line)) if requete.status_code == 200: print("[*] Mot de passe {0} valide !".format(line)) mot_de_pase = line break if args.connexion == 1: pass else: lg.debug("[*] Mot de passe {0} invalide.".format(line)) else: print( "Le système d'authentification est incorrect ou n'est pas supporté" )
def senddata(to_num, msg): auth = HTTPBasicAuth(API_KEY, API_SECRET) data = { "from": { "type": "whatsapp", "number": SANDBOX_NUMBER }, "to": { "type": "whatsapp", "number": to_num }, "message": { "content": { "type": "text", "text": msg } } } try: data = requests.post(URL, auth=auth, json=data) log.info(data.json()) except Exception as e: ConnectionError(e) return
def __init__(self, login, password): self.auth = HTTPBasicAuth(login, password)
def store_clients(): clients = read_clients() for client in clients: # TODO: verify request errors requests.post(URL, json=client, auth=HTTPBasicAuth(USERNAME, PASSWORD)) print('Clients loaded')
def read_client(): # TODO: read clients from couchDB clients = requests.get('http://127.0.0.1:5984/club_de_videos/_design/videos/_view/clients',auth=HTTPBasicAuth(USERNAME, PASSWORD)) json_data = json.loads(clients.content) return json_data
def store_movies(): movies = read_movies() for movie in movies: movie.update({"type": "movie"}) requests.post(URL, json=movie, auth=HTTPBasicAuth(USERNAME, PASSWORD)) print('Movies Loaded!!!')
#!/usr/bin/python3 """0x11 - 10""" from requests.models import HTTPBasicAuth import requests import sys if __name__ == "__main__": respy = requests.get("https://api.github.com/user", auth=HTTPBasicAuth( sys.argv[1], sys.argv[2])) iddy = respy.json().get("id") print(iddy)
#!/usr/bin/python3 """This module creates a python script to interact with a url""" from requests.models import HTTPBasicAuth if __name__ == "__main__": import requests from sys import argv response = requests.get("https://api.github.com/user", auth=HTTPBasicAuth(argv[1], argv[2])) print(response.json().get("id"))
def add_balance(vendor, number, amount): log = PrintingQuotaLog( user=vendor, account=number, type=PrintingQuotaLog.ADD, status=PrintingQuotaLog.PENDING, ) log.save() try: request = requests.post( f"https://qpilot.rbg.tum.de:9779/transfer/for-card-number/{number}/create", data={ "reasonForTransfer": "Skriptentool | testing" if settings.DEBUG else "Skriptentool", "amountOfMoney": amount, }, auth=HTTPBasicAuth(settings.QPILOT_USERNAME, settings.QPILOT_PASSWORD), timeout=5, ) except ConnectTimeout: log.status = PrintingQuotaLog.TIMEOUT log.save() raise TypeError try: request.raise_for_status() except HTTPError as error: if request.status_code == 401: log.status = PrintingQuotaLog.UNAUTHORIZED log.save() raise TypeError if request.status_code == 422: log.status = PrintingQuotaLog.UNKNOWN_NUMBER log.save() raise TypeError raise error log.status = PrintingQuotaLog.SUCCESS log.save() with translation.override(settings.LANGUAGE_CODE): send_mail( subject=format_lazy( "[Skriptentool] {}", capfirst(_("printing quota booked")), ), message=render_to_string( "core/mail/printing_quota_booked.txt", { "vendor": vendor, "number": number, "amount": amount }, ), from_email=settings.DEFAULT_FROM_EMAIL, recipient_list=settings.REFERENT_EMAILS, )