コード例 #1
0
    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
コード例 #2
0
ファイル: threattracking.py プロジェクト: f0r3ns1cat0r/yeti
    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
コード例 #3
0
ファイル: tasks.py プロジェクト: maznu/pinder
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)
コード例 #4
0
ファイル: base.py プロジェクト: kindsof/hammock
 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)
コード例 #5
0
ファイル: rest.py プロジェクト: ntnu-ai-lab/esnn-aqcbr
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
コード例 #6
0
ファイル: backend.py プロジェクト: Reddine/orkg-pypi
 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)
コード例 #7
0
ファイル: pinder.py プロジェクト: maznu/pinder
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))
コード例 #8
0
    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
コード例 #9
0
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
コード例 #10
0
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))
コード例 #11
0
 def __init__(self, base_url, user, apikey):
     self.user = user
     self.apikey = apikey
     self.client = hammock.Hammock(base_url, append_slash=True)
コード例 #12
0
ファイル: restless.py プロジェクト: bdragon300/koifish
 def start(self, **kwargs):
     params = self.config
     params.update(kwargs)
     return hammock.Hammock(**params)
コード例 #13
0
ファイル: registry.py プロジェクト: nodepy/nodepy
 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
コード例 #14
0
ファイル: app.py プロジェクト: l-grebe/hammock
#! /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,
    ]
コード例 #15
0
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')
コード例 #16
0
ファイル: jobimtext.py プロジェクト: yz9675/jobimtext-api
 def __init__(
         self,
         api_url='http://ltmaggie.informatik.uni-hamburg.de/jobimviz/ws'):
     self.api = hammock.Hammock(api_url)
コード例 #17
0
ファイル: app.py プロジェクト: wh0/ddproxy
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:
コード例 #18
0
        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):
コード例 #19
0
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)
コード例 #20
0
 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