def main(argv): parser = create_option_parser() (options, args) = parser.parse_args() try: if not options.bucket_name: parser.print_help() return 1 if not options.key: parser.print_help() return 1 params = get_params(options) client = HttpClient(options.host, options.port) if options.bucket_type: context = "/types/{}/buckets/{}/keys/{}/".format( client.escape_slash(options.bucket_type), client.escape_slash(options.bucket_name), client.escape_slash(options.key)) else: context = "/buckets/{}/keys/{}/".format( client.escape_slash(options.bucket_name), client.escape_slash(options.key)) response = client.get(context, params=params) client.pretty_print_response(response, options.verbose, options.b64) return 0 except Exception as e: print("An error occurred creating {{{{{}, {}}}, {}}}: {}".format( options.bucket_type, options.bucket_name, options.key, e)) #import traceback #traceback.print_exc() return -1
def __init__(self, server_host, server_port=None, username="******", password="******", use_tls=False, version=API_CURRENT_VERSION): """ Creates a Resource object that provides API endpoints. @param server_host: The hostname of the Cloudera Manager server. @param server_port: The port of the server. Defaults to 7180 (http) or 7183 (https). @param username: Login name. @param password: Login password. @param use_tls: Whether to use tls (https). @param version: API version. @return: Resource object referring to the root. """ self._version = version protocol = use_tls and "https" or "http" if server_port is None: server_port = use_tls and 7183 or 7180 base_url = "%s://%s:%s/api/v%s" % \ (protocol, server_host, server_port, version) client = HttpClient(base_url, exc_class=ApiException) client.set_basic_auth(username, password, API_AUTH_REALM) client.set_headers({"Content-Type": "application/json"}) Resource.__init__(self, client)
def __init__(self, top_level_classifier_host="ml-services.production.indix.tv", threshold=0.75): self.threshold = threshold self.classifier_query = ClassifierQuery("http", top_level_classifier_host, "/api/classify") self.client = HttpClient()
def get_value(host, port, bucket_type, bucket_name, key): #quoted_key = urllib.quote(key.encode('utf8'), safe="") context = "/types/{}/buckets/{}/keys/{}".format( HttpClient.escape_slash(bucket_type), HttpClient.escape_slash(bucket_name), HttpClient.escape_slash(key) ) riak_util.log("Context: {}".format(context)) client = HttpClient(host, port) return client.get(context)['body']
def __init__(self, **kwargs): super().__init__(**kwargs) """self.pizzas = [ Pizza("4 fromages", "chèvre, emmental, brie, comté", 9.5, True), Pizza("Chorizo", "tomates, chorizo, parmesan", 11.2, False), Pizza("Calzone", "fromage, jambon, champignons", 10, False) ]""" HttpClient().get_pizzas(self.on_server_data, self.on_server_error)
def on_parent(self, widget, parent): print("on_parent event -> full layout available") pizzas_json = StorageManager().get_data( self.STORAGE_FILENAME) # get pizzas from file self.recycleView.data = Pizza.build_list_data_for_rw(pizzas_json) HttpClient().get_pizzas(self.on_server_data, self.on_error_data, self.on_failure_data, self.on_progress_data) print( "HttpClient().get_pizzas is called to get pizzas from web service")
def get_keys(host, port, bucket): bucket_type, bucket_name = bucket context = "/types/{}/buckets/{}/keys?keys=true".format( HttpClient.escape_slash(bucket_type), HttpClient.escape_slash(bucket_name)) client = HttpClient(host, port) body = client.get(context)['body'] log("Context: {} BODY: {}".format(context, body)) data = json.loads(body.decode()) return data['keys']
def get_bucket_names(host, port, bucket_type): context = "/types/{}/buckets?buckets=true".format(bucket_type) client = HttpClient(host, port) try: data = json.loads(client.get(context)['body'].decode()) except Exception as e: print( "An error ocurred decoding JSON payload from request for bucket names. Error: {}; body: {}" .format(e, client.get(context)['body'])) #print("data: {}".format(data)) return data['buckets']
def main(argv): parser = create_option_parser() (options, args) = parser.parse_args() try: (options, args) = parser.parse_args() client = HttpClient(options.host, options.port) response = client.post("/reboot", "") client.pretty_print_response(response, False) return 0 except Exception as e: import traceback traceback.print_exc() return -1
def main(argv): try: path = argv[0] except: raise TypeError(HELP) try: opts, args = getopt.getopt(argv[1:], "hs:p:t") except getopt.GetoptError: raise TypeError(HELP) server = None port = None transport = None for opt, arg in opts: if opt == '-h': raise TypeError(HELP) elif opt == '-s': server = arg elif opt == '-p': port = arg elif opt == '-t': transport = arg if not server: server = "127.0.0.1" # Open connection with scribe zipkin = None if (transport == 'scribe'): zipkin = ZipkinScribeClient(port, server) if not port: port = 9410 else: transport = "http" zipkin = HttpClient(port, server) if not port: port = 9411 # Create TraceCollection and add trace: traces = TraceCollection() trace_handle = traces.add_trace(path, "ctf") if trace_handle is None: raise IOError("Error adding trace") print("Sending traces to " + server + ":" + port + " using " + transport + "\n") zipkin.send_annotations(traces.events) print("Done sending\n") return
def load_srv_json(file, srv_url=None): global HTTP_CLIENT if not srv_url: srv_url = updates_url() file_url = srv_url + file + '.json' try: if not HTTP_CLIENT: HTTP_CLIENT = HttpClient() return HTTP_CLIENT.get_json(file_url) except Exception as exc: LOG.exc(exc, 'Error loading server data: %s' % file) return None finally: manage_memory()
def get(host, path): """Sends HTTP GET using HttpClient and returns the request response body. :param host: host ip addr :param path: resource endpoint path :return: response body """ print('Sending GET ' + path + ' HTTP/1.1 request to ' + host) window.refresh() c = HttpClient(49512) req = c.create_get_request(host, path) logger.debug('GET request created.') logger.debug(req) res = c.request(bytes(req), host) print('Response: ' + res.split(b'\r\n')[0].decode()) window.refresh() return res
def main(argv): parser = create_option_parser() (options, args) = parser.parse_args() try: (options, args) = parser.parse_args() if not options.bucket_name: parser.print_help() return 1 if not options.key: parser.print_help() return 1 if not options.value and not options.file: parser.print_help() return 1 params = get_params(options) client = HttpClient(options.host, options.port) if options.bucket_type: context = "/types/{}/buckets/{}/keys/{}/".format( client.escape_slash(options.bucket_type), client.escape_slash(options.bucket_name), client.escape_slash(options.key)) else: context = "/buckets/{}/keys/{}/".format( client.escape_slash(options.bucket_name), client.escape_slash(options.key)) vclock = None if not options.force: result = client.get(context) if result['status'] != 404: if 'X-Riak-Vclock' in result['headers']: vclock = result['headers']['X-Riak-Vclock'] body = get_data(options) headers = {'X-Riak-Vclock': vclock} if vclock else {} response = client.put(context, body=body, content_type=options.content_type, headers=headers, params=params) client.pretty_print_response(response, options.verbose) return 0 except Exception as e: print("An error occurred creating {{{{{}, {}}}, {}}}: {}".format( options.bucket_type, options.bucket_name, options.key, e)) import traceback traceback.print_exc() return -1
def main(argv): parser = create_option_parser() (options, args) = parser.parse_args() try: (options, args) = parser.parse_args() client = HttpClient(options.host, options.port) response = client.get("/config/wifi?param=mode") print("mode: %s" % response['body']) response = client.get("/config/wifi?param=ssid") print("ssid: %s" % response['body']) response = client.get("/config/wifi?param=device_name") print("device_name: %s" % response['body']) #client.pretty_print_response(response, False) return 0 except Exception as e: import traceback traceback.print_exc() return -1
def main(argv): parser = create_option_parser() (options, args) = parser.parse_args() try: (options, args) = parser.parse_args() client = HttpClient(options.host, options.port) response = client.get("/config/camera?param=frame_size") print("frame_size: %s" % response['body']) response = client.get("/config/camera?param=jpeg_quality") print("jpeg_quality: %s" % response['body']) response = client.get("/config/camera?param=flash") print("flash: %s" % response['body']) #client.pretty_print_response(response, False) return 0 except Exception as e: import traceback traceback.print_exc() return -1
def perform_software_update(): global HTTP_CLIENT if not HTTP_CLIENT: HTTP_CLIENT = HttpClient() machine.WDT() manage_memory() version_data = load_version() device_type = get_device_type() srv_url = updates_url() srv_index = load_srv_json('index', srv_url=srv_url) machine.resetWDT() srv_versions = load_srv_json('devices', srv_url=srv_url) machine.resetWDT() if srv_index: for path, entry in srv_index.items(): if 'devices_types' in entry and 'base' not in entry[ 'devices_types'] and device_type not in entry[ 'devices_types']: continue if path in version_data['files'] and version_data['files'][ path] == entry['hash']: continue local_path = entry['path'] if 'path' in entry else path print(local_path) ensure_file_path(local_path) file_url = srv_url + 'software/' + path print(file_url) while version_data['files'].get(path) != entry['hash']: if HTTP_CLIENT.get_to_file(file_url, 'file_buf'): try: uos.remove(local_path) except OSError: pass uos.rename('file_buf', local_path) if version_data['hash']: version_data['hash'] = None version_data['files'][path] = entry['hash'] save_version(version_data) print('complete') machine.resetWDT() version_data['hash'] = srv_versions[device_type] version_data['update'] = False save_version(version_data) machine.reset()
def post(host, path, data): """Sends POST request using HttpClient and the data from GUI form. :param host: host ip addr :param path: resource endpoint path :param data: data to be sent as body of the POST request :return: HTTP response body """ cover = open(data, 'rb').read() print('Sending POST ' + path + ' HTTP/1.1 request to ' + host) window.refresh() print('RSTEG not activated.') window.refresh() c = HttpClient(49512) req = c.create_post_request(host, path, cover, 'image/jpg') res = c.request(bytes(req), host) print('Response: ' + res.split(b'\r\n')[0].decode()) window.refresh() return res
def rpost(host, path, data, secret_data, rprob): """Sends rPOST request using HttpClient and the data from GUI form. :param host: host ip addr :param path: resource endpoint path :param data: data to be sent as body of the POST request :param secret_data: secret to be sent using the RSTEG mechanism :param rprob: retransmission probability :return: HTTP response body """ cover = open(data, 'rb').read() secret = open(secret_data, 'rb').read() print('Sending POST ' + path + ' HTTP/1.1 request to ' + host) print('Using RSTEG to send secret.') window.refresh() c = HttpClient(float(rprob), 49512) req = c.create_post_request(host, path, cover, 'image/jpg') res = c.rsteg_request(bytes(req), secret, host) print('Response: ' + res.split(b'\r\n')[0].decode()) return res
def niceview_svr(num=10): ''' 同步实现 图片获取 :param num: 图片数量 :return: 状态码和图片信息, ''' header = { "apikey": "af8a128ea2f8f494cf7ab9456208a762", "Content-Type": "application/json" } host = 'apis.baidu.com' url = '/txapi/mvtp/meinv?num=%d' % num http_cli = HttpClient(host, 80, 30) http_res = http_cli.send_request(url, 'GET', header=header) ret = {} ret["status"] = http_res["status"] if ret["status"] != 200: return ret ret["picList"] = http_res["body"]["newslist"] return ret
def main(): endpoint = getEndpoint() httpClient = HttpClient(endpoint) while (True): print(""" 1: Start New Session 2: Join Session""") cmd = input() if cmd == "1": sessionInfo = startNewSession(httpClient) sessionInfo and waitForPlayers(sessionInfo, httpClient) and startSession( sessionInfo, httpClient) elif cmd == "2": print("Enter SessionId") sessionId = input() sessionInfo = joinSession(httpClient, sessionId) sessionInfo and waitForPlayers(sessionInfo, httpClient) and startSession( sessionInfo, httpClient) else: print("invalid input")
def main(argv): parser = create_option_parser() (options, args) = parser.parse_args() try: (options, args) = parser.parse_args() client = HttpClient(options.host, options.port) params = {} if options.mode: params['mode'] = options.mode if options.ssid: params['ssid'] = options.ssid if options.password: params['password'] = options.password if options.device_name: params['device_name'] = options.device_name response = client.post("/config/wifi", "", params=params) client.pretty_print_response(response, False) return 0 except Exception as e: import traceback traceback.print_exc() return -1
def main(argv): parser = create_option_parser() (options, args) = parser.parse_args() try: (options, args) = parser.parse_args() client = HttpClient(options.host, options.port, verbose=options.verbose) params = {} if options.frame_size: params['frame_size'] = options.frame_size if options.jpeg_quality: params['jpeg_quality'] = options.jpeg_quality if options.flash: params['flash'] = options.flash response = client.post("/config/camera", "", params=params) client.pretty_print_response(response, False) return 0 except Exception as e: import traceback traceback.print_exc() return -1
if not os.path.exists(DUMPS_FOLDER): os.makedirs(DUMPS_FOLDER) if not os.environ.get(WEBSITE_HOSTNAME): os.environ[WEBSITE_HOSTNAME] = f'localhost-main-{now()}' if 'email' in watch_types: store = CredentialsStore() def start_mail_checker_thread(email): mail_checker = MailChecker(store, email, config, tg_bot) return mail_checker.start_loop(args.nb_attempts) mail_checkers = list(map(lambda data: start_mail_checker_thread(data['email']), form_data)) logger.info(f"Waiting for {len(mail_checkers)} email checking threads to finish") for th in mail_checkers: th.join() if 'website' in watch_types: http_client = HttpClient() #browsers = list(map(lambda data: Browser(config, data, tg_bot, http_client), form_data)) metrics = Metrics(export_metrics=False) watcher = WatcherMultislot(tg_bot, http_client, metrics, config, args.parallelism) watcher.start_loop( max_attempts=args.nb_attempts ) logger.info(f"Waiting for {len(watcher.form_submit_threads)} submit actions to finish") for th in watcher.form_submit_threads: th.join() logger.info("Done. Exiting")
def delete(host, port, bucket_type, bucket_name, key): context = "/types/{}/buckets/{}/keys/{}".format( HttpClient.escape_slash(bucket_type), HttpClient.escape_slash(bucket_name), HttpClient.escape_slash(key)) client = HttpClient(host, port) return client.delete(context)
def __init__(self, config_path): self.client = HttpClient(config_path)
]) ], [sg.Button('Submit'), sg.Button('Clear log')]] upper_menu_layout = [['Help'], ['About']] # Create the window window = sg.Window('RSTEG TCP', layout, location=(1920 / 3, 1080 / 3), auto_size_text=14) # Render flags http_visible_flag = False tcp_visible_flag = False post_details_flag = False c = HttpClient(49512) # Window Event Loop while True: event, values = window.read() # Quit event if event == sg.WINDOW_CLOSED: break # Render HTTP frame event if event == 'http': http_visible_flag = not http_visible_flag window['http_frame'].update(visible=http_visible_flag) window['tcp_frame'].update(visible=False) window.refresh() # Render POST details frame event if event == 'http_request': if values['http_request'] == 'POST':
import argparse from html_parser import HTMLStatsCollector from http_client import HttpClient argp = argparse.ArgumentParser() argp.add_argument('-n', '--hostname', help='Host to request. For example: "python.org"') argp.add_argument( '-p', '--path', help='URL path after hostname. For example: "search/?q=macos&submit="') args = argp.parse_args() client = HttpClient() response = client.request('GET', host=args.hostname, path=args.path) parser = HTMLStatsCollector() parser.feed(response.body) result = parser.get_result() print('Tags:') for key, value in result['tags'].items(): print(f'{key}: {value}') print() print(f'Most frequent tag: {result["most_frequent"]}\n') print('Links:') for link in result['links']: print(link) print()
def __init__(self): self.client = HttpClient()
from http_client import HttpClient from lcg_cracker import LCGCracker from mt_cracker import MtCracker config = { "create_acc_url": "http://95.217.177.249/casino/createacc", "account_id": "vedaukr", "url": "http://95.217.177.249/casino/play{0}" } client = HttpClient(config) #LCGCracker(client).crack() MtCracker(client).crack()
def __init__(self, network_controller): LOG.info("LenferDevice init") self._schedule = None self._network = network_controller self.mode = None self.status = { "wlan": None, "factory_reset": False, "wlan_switch": False, "ssid_failure": False, "ssid_delay": False, "srv_req_pending": False } self.log_queue = [] self.busy = False self._conf = load_json('conf.json') self.settings = load_json('settings.json') self._http = HttpClient() if not self.settings: self.load_def_settings() if self.settings.get('mode'): self.mode = self.settings['mode'] if self._conf.get('wlan_switch'): self._wlan_switch_button = Pin(self._conf['wlan_switch'], Pin.IN, Pin.PULL_UP, handler=self.wlan_switch_irq, trigger=Pin.IRQ_FALLING) if self._conf.get('factory_reset'): self._factory_reset_button = Pin(self._conf['factory_reset'], Pin.IN, handler=self.factory_reset_irq, trigger=Pin.IRQ_FALLING | Pin.IRQ_RISING) self.modules = {} self.i2c = [ I2C(scl=Pin(i2c_conf['scl']), sda=Pin(i2c_conf['sda'])) for i2c_conf in self._conf['i2c'] ] LOG.info('I2C init') self.leds = { led: Pin(pin_no, Pin.OUT) for led, pin_no in self._conf['leds'].items() } self.id = load_json('id.json') if 'debug' in self.id and self.id['debug']: self.server_uri = SERVER_URI_DEV else: self.server_uri = SERVER_URI for led in self.leds.values(): led.value(0) self.schedule = Schedule() manage_memory() machine.resetWDT() if 'rtc' in self._conf['modules'] and self.module_enabled( self._conf['modules']['rtc']): try: from timers import RtcController self.modules['rtc'] = RtcController( self, self._conf['modules']['rtc']) self.modules['rtc'].get_time(set_rtc=True) LOG.info('RTC init') except Exception as exc: LOG.exc(exc, 'RTC initialization error') machine.resetWDT() manage_memory() if 'climate' in self._conf['modules'] and self.module_enabled( self._conf['modules']['climate']): try: from climate import ClimateController self.modules['climate'] = ClimateController( self, self._conf['modules']['climate']) LOG.info('ClimateController init') except Exception as exc: LOG.exc(exc, 'Climate initialization error') if self._conf['modules']['climate'].get('obligatory'): LOG.error( 'Obligatory module initialization fail -- machine reset' ) machine.reset() machine.resetWDT() manage_memory() if 'power_monitor' in self._conf['modules'] and self.module_enabled( self._conf['modules']['power_monitor']): try: from power_monitor_controller import PowerMonitor self.modules['power_monitor'] = PowerMonitor( self, self._conf['modules']['power_monitor']) LOG.info('PowerMonitor init') except Exception as exc: LOG.exc(exc, 'PowerMonitor initialization error') if self._conf['modules']['power_monitor'].get('obligatory'): LOG.error( 'Obligatory module initialization fail -- machine reset' ) machine.reset() machine.resetWDT() manage_memory() if 'feeder' in self._conf['modules'] and self.module_enabled( self._conf['modules']['feeder']): try: from feeder import FeederController self.modules['feeder'] = FeederController( self, self._conf['modules']['feeder']) LOG.info('Feeder init') except Exception as exc: LOG.exc(exc, 'Feeder initialization error') machine.resetWDT() manage_memory() if 'gate' in self._conf['modules'] and self.module_enabled( self._conf['modules']['gate']): try: from gate_controller import GateController self.modules['gate'] = GateController( self, self._conf['modules']['gate']) LOG.info('Gate init') except Exception as exc: LOG.exc(exc, 'Gate initialization error') machine.resetWDT() manage_memory() if 'relay_switch' in self._conf['modules'] and self.module_enabled( self._conf['modules']['relay_switch']): try: from relay_switch import RelaySwitchController self.modules['relay_switch'] = RelaySwitchController( self, self._conf['modules']['relay_switch']) LOG.info('Relay init') except Exception as exc: LOG.exc(exc, 'RelaySwitch initialization error') machine.resetWDT() manage_memory() LOG.info(self.modules)