def authenticate(self, username, api_key, auth_token=None): """Authenticate this connection using the given credentials. :param username: SoftLayer username :param api_key: SoftLayer API Key :param auth_token: (optional) Starting auth token """ auth_endpoint = '/'.join((self.endpoint, 'v1', self.account_id, 'auth')) auth = QueueAuth(auth_endpoint, username, api_key, auth_token=auth_token) auth.auth() self.auth = auth
def authenticate(self, username, api_key, auth_token=None): """ Make request. Generally not called directly :param username: SoftLayer username :param api_key: SoftLayer API Key :param auth_token: (optional) Starting auth token """ auth_endpoint = '/'.join((self.endpoint, 'v1', self.account_id, 'auth')) auth = QueueAuth(auth_endpoint, username, api_key, auth_token=auth_token) auth.auth() self.auth = auth
def authenticate(self, username, api_key, auth_token=None): """ Make request. Generally not called directly :param username: SoftLayer username :param api_key: SoftLayer API Key :param auth_token: (optional) Starting auth token """ auth_endpoint = '/'.join( (self.endpoint, 'v1', self.account_id, 'auth')) auth = QueueAuth(auth_endpoint, username, api_key, auth_token=auth_token) auth.auth() self.auth = auth
def login(self): response = rq.get('{}/login'.format(self.url), auth=auth(self.user, self.passwd)) if response.status_code == 200: self.x = get_x(response.headers) return response.json()['message'] return f'Something went wrong: {response.text}, {response.status_code}'
def get_exchange_names(): url = "http://localhost:15672/api/exchanges" response = requests.get(url, auth=auth('guest', 'guest')) array = response.json() return [exchange["name"] for exchange in array if exchange['vhost'] == '/']
def send_text(self, name, text: str): if self.key is None or self.aes is None: self.init_session() headers = { 'Content-type': 'application/octet-stream', 'Session-Code': self.get_code(), 'f-value': f(self.x) } encrypted = self.aes.encrypt(text) if self.debug: print('Raw data:', text) print('Encrypted data:', encrypted) response = rq.post('{}/store?name={}'.format(self.url, name), encrypted, headers=headers, auth=auth(self.user, self.passwd)) message = response.json() if response.status_code == 200: self.x = get_x(response.headers) if self.debug: print('Got x=', self.x) return message['message'] elif response.status_code == 401: self.key = None self.aes = None return self.send_text(name, text) else: raise Exception(message['error'])
def check_alive(): creds = auth('guest', 'guest') url = "http://localhost:15672/api/aliveness-test/%2F" response = get(url, auth=creds) status = response.json() print("aliveness test returned with '{0}'".format(response.status_code)) print(status)
def quick_check(domain, user, password): """Validate the server details""" try: orthanc = RestClient(domain, auth=auth(user, password)) orthanc.get_changes(last=True) except: return False else: return True
def transition_first_sync(self): """Import and create all current patients and studies on remote DICOM server """ pool = Pool() Patient = pool.get("gnuhealth.orthanc.patient") Study = pool.get("gnuhealth.orthanc.study") Config = pool.get("gnuhealth.orthanc.config") orthanc = RestClient(self.start.domain, auth=auth(self.start.user, self.start.password)) try: patients = orthanc.get_patients(expand=True) studies = orthanc.get_studies(expand=True) except HTTPError as err: if err.response.status_code == 401: self.result.result = "Invalid credentials provided" logger.exception("Invalid credentials provided") else: self.result.result = "Invalid domain provided" logger.exception("Request returned error status code") except: self.result.result = "Invalid domain provided" logger.exception("Other error occurred") else: new_server = { "label": self.start.label, "domain": self.start.domain, "user": self.start.user, "password": self.start.password, } server, = Config.create([new_server]) Patient.create_patients(patients, server) Study.create_studies(studies, server) server.last = orthanc.get_changes(last=True).get("Last") server.sync_time = datetime.now() server.validated = True Config.save([server]) self.result.result = "Successfully added and synced <{}>".format( server.label) logger.info( "<{}> sync complete: {} new patients, {} new studies".format( server.label, len(patients), len(studies))) finally: return "result"
def get_key(self) -> str: gmc = GMC() a, N = gmc.get_pub_key() response = rq.post('{}/key'.format(self.url), json={ 'a': a, 'N': N }, auth=auth(self.user, self.passwd), headers={ 'Session-Code': self.get_code(), 'f-value': f(self.x) }) if response.status_code == 200: self.x = get_x(response.headers) if self.debug: print('Got x=', self.x) decoded = response.json()['info'] return gmc.decode(decoded) else: raise Exception(response.json()['error'])
def get_text(self, name: str): if self.key is None or self.aes is None: self.init_session() response = rq.get('{}/file?name={}'.format(self.url, name), auth=auth(self.user, self.passwd), headers={ 'Session-Code': self.get_code(), 'f-value': f(self.x) }) if response.status_code == 200: self.x = get_x(response.headers) decrypted = self.aes.decrypt(response.content) if self.debug: print('Got x=', self.x) print('Encrypted data:', response.content) print('Decrypted data:', decrypted) return decrypted.decode('utf-8') elif response.status_code == 401: self.key = None self.aes = None return self.get_text(name) else: raise Exception(response.json()['error'])
HOURS_RE = re.compile('(?P<num>[0-9]+) hours') MINS_RE = re.compile('(?P<num>[0-9]+) min') def parse_delta(buffer): if ' hours' in buffer: return int(HOURS_RE.match(buffer).groupdict()['num']) * 60 elif ' min' in buffer: return int(MINS_RE.match(buffer).groupdict()['num']) sent = [] for branch in BRANCHES: kwargs = {} if CGIT_PROTECTED: kwargs['auth'] = auth(*CGIT_CREDS) response = requests.get(CGIT_LOG_URL % branch, **kwargs) soup = bs(response.content) for entry in soup.find_all('table')[-1].find_all('tr')[1:]: timestamp, message, author, fcount, lcount = entry.find_all('td') message = message.find_all('a')[0].text if TOKEN not in message or message in sent: continue author = author.text timestamp = timestamp.find_all('span')[0].text
active_wireless = [active_wireless_raw[a:a+9] for a in range(0, len(active_wireless_raw), 9)] # convert some stuff to int, add time current_time = int(time.time()) active_wireless = map(lambda l: l[:5] + map(int, l[5:]) + [current_time], active_wireless) if not dic: return active_wireless wireless_dicts = [dict(zip(keys, each)) for each in active_wireless] return wireless_dicts ### Tests myauth = auth(username, password) probe = probe_router(url, myauth) mac_set = set([x[0].lower() for x in probe]) special_mac = 'FC:C2:DE:AA:B5:E9'.lower() try: if special_mac in mac_set: print(action(False)) else: print(action(True)) except Exception as e: print('bad') cursor.executemany('insert into wireless_hosts values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', probe) res = connection.commit()
import ConnectLocal from requests import get from requests.auth import HTTPBasicAuth as auth creds = auth('guest', 'guest') url = "http://localhost:15672/api/aliveness-test/%2F" #aliveness def check_alive(): response = requests.get(url, creds) status = response.json() print("aliveness test returned with {0}".format(response.status_code)) print(status) #tcp def connect(): return ConnectLocal.connect_heartbeat() while True: channel = connect() try: check_alive() channel.basic_publish("", "pika_queue", body="aliveness") except: print("Not alive -- action is required") v=raw_input("press Ctrl+C to stop")
import ConnectLocal from requests import get from requests.auth import HTTPBasicAuth as auth creds = auth("guest", "guest") url = "http://localhost:15672/api/aliveness-test/%2F" #aliveness def check_alive(): response = get(url, creds) status = response.json() print("aliveness test returned with '{0}".format(response.status_code)) print(status) #tcp def connect(): return ConnectLocal.connect_heartbeat() while (True): channel = connect() try: check_alive() channel.basic_publish("", "pika_queue", body="aliveness") except: print("not alive--action required") v = input("press ctrl+c to stop or any key to continue publishing")
def sync(cls, servers=None): """Sync from changes endpoint""" pool = Pool() patient = pool.get("gnuhealth.orthanc.patient") study = pool.get("gnuhealth.orthanc.study") if not servers: servers = cls.search([("domain", "!=", None), ("validated", "=", True)]) logger.info("Starting sync") for server in servers: if not server.validated: continue logger.info("Getting new changes for <{}>".format(server.label)) orthanc = RestClient(server.domain, auth=auth(server.user, server.password)) curr = server.last new_patients = set() update_patients = set() new_studies = set() update_studies = set() while True: try: changes = orthanc.get_changes(since=curr) except: server.validated = False logger.exception("Invalid details for <{}>".format(server.label)) break for change in changes["Changes"]: type_ = change["ChangeType"] if type_ == "NewStudy": new_studies.add(change["ID"]) elif type_ == "StableStudy": update_studies.add(change["ID"]) elif type_ == "NewPatient": new_patients.add(change["ID"]) elif type_ == "StablePatient": update_patients.add(change["ID"]) else: pass curr = changes["Last"] if changes["Done"] == True: logger.info("<{}> at newest change".format(server.label)) break update_patients -= new_patients update_studies -= new_studies if new_patients: patient.create_patients( [orthanc.get_patient(p) for p in new_patients], server ) if update_patients: patient.update_patients( [orthanc.get_patient(p) for p in update_patients], server ) if new_studies: study.create_studies( [orthanc.get_study(s) for s in new_studies], server ) if update_studies: study.update_studies( [orthanc.get_study(s) for s in update_studies], server ) server.last = curr server.sync_time = datetime.now() logger.info( "<{}> sync complete: {} new patients, {} update patients, {} new studies, {} updated studies".format( server.label, len(new_patients), len(update_patients), len(new_studies), len(update_studies), ) ) cls.save(servers)