def update(self): params = {'key': yeti_config.get('threattracking', 'google_api_key')} # , 'includeGridData': 'True'} - we don't want to do that. 200Mo file. base = "https://sheets.googleapis.com/v4/spreadsheets/" + yeti_config.get( 'threattracking', 'sheet_key') self.api = hammock.Hammock(base, params=params) r = self.api.GET() if r.status_code != 200: raise requests.ConnectionError( 'Return code for {query} is {code}'.format(query=r.request.url, code=r.status_code)) sheets = r.json()['sheets'] for s_p in sheets: s = s_p['properties'] title = s['title'] if title in [ 'README', 'Home', '_Malware', '_Download', '_Schemes', '_Sources' ]: continue size = s['gridProperties'] actors_list_info = self.each_sheet_work(s) self.create_entities(title, actors_list_info) return
def update(self): """ """ params = {"key": yeti_config.get("threattracking", "google_api_key")} # , 'includeGridData': 'True'} - we don't want to do that. 200Mo file. base = "https://sheets.googleapis.com/v4/spreadsheets/" + yeti_config.get( "threattracking", "sheet_key") self.api = hammock.Hammock(base, params=params) if False: r = self.api.GET() if r.status_code != 200: raise requests.ConnectionError( "Return code for {query} is {code}".format( query=r.request.url, code=r.status_code)) sheets = r.json()["sheets"] json.dump(sheets, open("actor.sheets.json", "w")) else: sheets = json.load(open("actor.sheets.json", "r")) # print(pprint.pformat(sheets)) for s_p in sheets: s = s_p["properties"] title = s["title"] if title in [ "Home", "_Malware", "_Download", "_Schemes", "_Sources" ]: continue size = s["gridProperties"] # print(title, size['columnCount'], size['rowCount']) actors_list_info = self.each_sheet_work(s) self.create_entities(title, actors_list_info) return
def _requests(rid, state, others=None): pinder = hammock.Hammock('http://127.0.0.1:8000', append_slash=True) current = pinder.api.requests(rid).GET() current = current.json() current['state'] = state result = pinder.api.requests(rid).PUT(data=current).json() pprint_color(result)
def before(self): self.api.add_sink(default_404) resources = importlib.import_module(self.RESOURCES) hammock.Hammock(self.api, resources, policy_file=self.POLICY, credentials_class=self.CREDENTIAL_CLASS, **self.RESOURCE_PARAMS)
def getRequest(host): """This function adds a amalgation function to a concept :param host: hostname of the API server (e.g. epicmonolith.duckdns.org:8080) :returns: The hammock object for CBR REST API :rtype: hammock object for CBR REST API """ api = hammock.Hammock("http://{}".format(host)) return api
def __init__(self, host=None, **kwargs): if host is not None and not host.startswith('http'): raise ValueError('host must begin with http or https') self.host = host if host is not None else 'http://127.0.0.1:8000' self.backend = hammock.Hammock(self.host).api self.resources = ResourcesClient(self) self.predicates = PredicatesClient(self) self.classes = ClassesClient(self) self.literals = LiteralsClient(self) self.stats = StatsClient(self) self.statements = StatementsClient(self) self.papers = PapersClient(self)
def main(): module = AnsibleModule( argument_spec=dict( state=dict(type='str', required=True, choices=['in-progress']), ), supports_check_mode=True ) state = module.params['state'] pinder = hammock.Hammock('http://127.0.0.1:8000') sessions = pinder.api.requests.GET(params='state={}'.format(state)).json()['results'] module.exit_json(sessions=sessions, msg=str(sessions))
def __init__(self, name, email, password, user_key, retries, api_version): """ Stores the resource name and API credentials and sets up the Hammock request chain for subsequent calls """ self.name = name self.email = email self.password = password self.user_key = user_key self.retries = retries self.api_version = api_version # set up the base Hammock request chain self.api = hammock.Hammock('https://pi.pardot.com/api') # initialise the api_key to None to flag that login is required self.api_key = None
def deploy_next_asg(ami): asgard = hammock.Hammock(ASGARD_HOST, auth=tuple(ASGARD_CREDENTIALS)) cluster = "{}-d0staging".format(CLOUD_APP) current_asg = asgard("us-east-1").cluster.show( cluster + ".json").GET().json()[0]["autoScalingGroupName"] param_dict = {"name": cluster, "imageId": ami, "trafficAllowed": "true"} next_asg = asgard("us-east-1").cluster.createNextGroup.POST( params=param_dict) if next_asg.status_code == 200: task = next_asg.url.split("/")[-1] status = "" while status not in ["completed", "failed"]: next_asg_result = asgard("us-east-1").task.show( "{}.json".format(task)).GET().json() status = next_asg_result["status"] # only delete the asg if we were able to create the new one successfully delete_asg_log = "" delete_asg_result = "" if status == "completed": delete_asg = asgard("us-east-1").cluster.delete.POST( params={"name": current_asg}) if delete_asg.status_code == 200: task = delete_asg.url.split("/")[-1] status = "" while status not in ["completed", "failed"]: delete_asg_result = asgard("us-east-1").task.show( "{}.json".format(task)).GET().json() status = delete_asg_result["status"] if delete_asg_result["log"]: delete_asg_log = "\n".join(i for i in delete_asg_result["log"]) if next_asg_result["log"]: next_asg_log = "\n".join(i for i in next_asg_result["log"]) message = next_asg_log + "\n\n" + delete_asg_log subject = "Asgard results for {}-{}".format(CLOUD_APP, DEV_PHASE) publish_to_sns(message, subject) return True
def main(): module = AnsibleModule(argument_spec=dict( sessions=dict(type='list', required=True), asn=dict(type='int', required=True), ), supports_check_mode=True) sessions = module.params['sessions'] asn = module.params['asn'] pinder = hammock.Hammock('http://127.0.0.1:8000', append_slash=True) result = [] for session in sessions: if session['sender']['isp']['asn'] == asn: session['sender_is_ready'] = True elif session['receiver']['asn'] == asn: session['receiver_is_ready'] = True else: raise Exception( "Couldn't figure out if I was the sender or the receiver") r = pinder.api.requests(session['id']).PUT(data=session) result.append(r.json()) module.exit_json(sessions=result, msg=str(result))
def __init__(self, base_url, user, apikey): self.user = user self.apikey = apikey self.client = hammock.Hammock(base_url, append_slash=True)
def start(self, **kwargs): params = self.config params.update(kwargs) return hammock.Hammock(**params)
def __init__(self, name, base_url, username=None, password=None): self.name = name self.base_url = base_url self.username = username self.password = password self.api = hammock.Hammock(base_url).api
#! /user/bin/env python from __future__ import absolute_import import os import hammock import sys import subprocess import tests.resources1 as resources1 import tests.base as tests_base api = hammock.Hammock( 'falcon', resources1, policy_file=os.path.join(os.path.abspath(os.path.dirname(__file__)), 'policy.json'), credentials_class=tests_base.TestCredentials, ) application = api.api # pylint: disable=invalid-name THIS_FILE = os.path.abspath(__file__.replace('.pyc', '.py')) def command(listen_port, app_file=None, procname='hammock-test'): app_file = app_file or THIS_FILE return [ 'uwsgi', '--http', ':{:d}'.format(listen_port), '--wsgi-file', app_file, '--need-app', '--procname', procname, ]
import falcon import hammock import resources application = falcon.API() hammock.Hammock(application, resources) # from werkzeug.contrib.profiler import ProfilerMiddleware # application = ProfilerMiddleware(application, profile_dir='profile')
def __init__( self, api_url='http://ltmaggie.informatik.uni-hamburg.de/jobimviz/ws'): self.api = hammock.Hammock(api_url)
import json import os import traceback import flask import hammock domains = json.loads(os.environ['DOMAINS']) cloudflare = hammock.Hammock('https://api.cloudflare.com/client/v4', headers={ 'X-Auth-Email': os.environ['CLOUDFLARE_EMAIL'], 'X-Auth-Key': os.environ['CLOUDFLARE_KEY'], }) def cloudflare_result(response): payload = response.json() if not payload['success']: raise Exception(payload) return payload['result'] app = flask.Flask(__name__) @app.route('/nic/update') def update(): if flask.request.authorization is None:
os.mkdir(build_path) resources_path = '{}/resources/'.format(build_path) if not os.path.exists(resources_path): os.mkdir(resources_path) sys.path.append(build_path) for i in range(1, 3): subprocess.check_output('cp -r tests/resources{}/* {}'.format( i, resources_path), shell=True) return importlib.import_module('resources') UnifiedClient = get_unified_client(BUILD_PATH) application = falcon.API() hammock.Hammock(application, get_unified_resources_package('build/cli-tests'), policy_file=os.path.abspath('tests/policy.json')) def cli(argv=sys.argv[1:], remove_ignored_commands=True, stdout=sys.stdout): app_class = type( 'App', (hammock.cli.App, ), {'REMOVE_COMMANDS_WITH_NAME_FALSE': remove_ignored_commands}) return app_class( UnifiedClient, stdout=stdout).run(['--url', 'http://localhost:{}'.format(PORT)] + argv) class Base(uwsgi_base.UwsgiBase):
if len(sys.argv) != 3: print >> sys.stderr, 'Usage: python %s zone subdomain' % sys.argv[0] sys.exit(1) zone_name = sys.argv[1] subdomain = sys.argv[2] def config_get(key): return subprocess.check_output(('heroku', 'config:get', key))[:-1] def config_set(key, value): subprocess.check_output(('heroku', 'config:set', '%s=%s' % (key, value))) cloudflare = hammock.Hammock('https://api.cloudflare.com/client/v4', headers={ 'X-Auth-Email': config_get('CLOUDFLARE_EMAIL'), 'X-Auth-Key': config_get('CLOUDFLARE_KEY') }) def cloudflare_result(response): payload = response.json() if not payload['success']: raise Exception(payload) return payload['result'] zones_result = cloudflare_result(cloudflare.zones.GET(params={'name': zone_name})) if len(zones_result) == 0: print >> sys.stderr, 'Zone %s not found' % zone_name sys.exit(1) else: zone_id = zones_result[0]['id'] dns_record_name = '%s.%s' % (subdomain, zone_name)
def __init__(self, api_key, project_id, version='head'): url_string = 'https://app.knowledgeowl.com/api/{0}'.format(version) self.knowledgeowl = hammock.Hammock(url_string, auth=(api_key, 'X'), headers={'Content-Type': 'application/json'}) self.project_id = project_id