ripe-api-client/ripe-api.py

162 lines
5.1 KiB
Python
Raw Normal View History

2019-02-10 11:22:58 +00:00
#!/usr/bin/env python3
2017-06-01 13:54:07 +00:00
import requests
import json
import yaml
import sys
import argparse
import tempfile
import os
import hashlib
from subprocess import call
2018-12-10 16:32:42 +00:00
config = os.path.join(os.path.dirname(os.path.realpath(__file__)),"config.yml")
2017-06-01 13:54:07 +00:00
# Read configuration
2018-12-10 16:32:42 +00:00
with open(config, 'r') as ymlfile:
2017-06-01 13:54:07 +00:00
cfg = yaml.load(ymlfile)
# Functions
def call_api(method, url, object_data=None):
headers = { 'Content-Type': 'application/json',
'Accept': 'application/json' }
response = requests.request(method, url, json=object_data, headers=headers,
params=cfg['params'])
if not response.text:
2019-02-10 11:22:58 +00:00
print("No response received (error %i)" % response.status_code)
2017-06-01 13:54:07 +00:00
sys.exit(1)
json_response=json.loads(response.text)
if "errormessages" in json_response:
for err in json_response['errormessages']['errormessage']:
if 'args' in err:
2019-02-10 11:22:58 +00:00
print(err['text'].replace('\n', ' ').replace('\r', '') \
% tuple([d['value'] for d in err['args']]))
2017-06-01 13:54:07 +00:00
else:
2019-02-10 11:22:58 +00:00
print(err['text'])
2017-06-01 13:54:07 +00:00
return json_response
# Print formatted output from JSON
def print_output(json, object_file):
if "objects" in json:
for attr in json['objects']['object'][0]['attributes']['attribute']:
object_file.write("%-20s %s\n" % (attr['name']+':',
attr['value']))
if object_file:
object_file.close()
def read_input(object_file):
attr = []
for line in object_file.readlines():
if not line: continue
2018-07-04 11:56:59 +00:00
attr.append({'name':line.split(':', 1)[0].strip(),
'value':line.split(':', 1)[1].strip() })
2017-06-01 13:54:07 +00:00
object_data = {
"objects": {
"object": [
{
"attributes": {
"attribute": attr
}
}
]
}
}
return object_data
# Get record
def get(args):
2019-02-10 11:22:58 +00:00
print("Getting %s object %s" % (args.type, args.key))
2017-06-01 13:54:07 +00:00
url = '/'.join((cfg['base_url'],args.type,args.key))
json_response=call_api("GET", url)
print_output(json_response, args.file)
return
# Delete record
def delete(args):
2019-02-10 11:22:58 +00:00
print("Deleting %s object %s" % (args.type, args.key))
2017-06-01 13:54:07 +00:00
url = '/'.join((cfg['base_url'],args.type,args.key))
json_response=call_api("DELETE", url)
return
# Create record
def create(args):
2019-02-10 11:22:58 +00:00
print("Creating %s object" % (args.type))
2017-06-01 13:54:07 +00:00
url = '/'.join((cfg['base_url'],args.type))
object_data = read_input(args.file)
json_response=call_api("POST", url, object_data)
print_output(json_response, sys.stdout)
return
# Update record
def update(args):
2019-02-10 11:22:58 +00:00
print("Updating %s object %s" % (args.type, args.key))
2017-06-01 13:54:07 +00:00
url = '/'.join((cfg['base_url'],args.type,args.key))
object_data = read_input(args.file)
json_response=call_api("PUT", url, object_data)
print_output(json_response, sys.stdout)
return
# Edit record
def edit(args):
tmp_fd, tmp_name = tempfile.mkstemp()
get(parser.parse_args(["get", args.type, args.key, tmp_name]))
EDITOR = os.environ.get('EDITOR','vim')
# Memory inefficient, but who cares?
2019-02-10 11:22:58 +00:00
hash1 = hashlib.md5(open(tmp_name).read().encode('utf-8')).hexdigest()
2017-06-01 13:54:07 +00:00
call([EDITOR, tmp_name])
2019-02-10 11:22:58 +00:00
hash2 = hashlib.md5(open(tmp_name).read().encode('utf-8')).hexdigest()
2017-06-01 13:54:07 +00:00
if hash1 != hash2:
update(parser.parse_args(["update", args.type, args.key, tmp_name]))
else:
2019-02-10 11:22:58 +00:00
print("Object unchanged, not updating")
2017-06-01 15:16:57 +00:00
os.unlink(tmp_name)
2017-06-01 13:54:07 +00:00
return
# Arguments parsing
# USAGE : ./ripe-api.py delete <TYPE> <KEY>
# ./ripe-api.py create <TYPE> <FILE>
# ./ripe-api.py update <TYPE> <KEY> <FILE>
# ./ripe-api.py get <TYPE> <KEY> <FILE>
# ./ripe-api.py edit <TYPE> <KEY>
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(help='Action to perform',dest='action')
2018-03-26 14:11:42 +00:00
parser_get = subparsers.add_parser('get', help='Get an object')
2017-06-01 13:54:07 +00:00
parser_get.add_argument('type', type=str, help='Object type')
parser_get.add_argument('key', type=str, help='Object identifier')
parser_get.add_argument('file', type=argparse.FileType('w'), help='Output file')
parser_delete = subparsers.add_parser('delete', help='Delete an object')
parser_delete.add_argument('type', type=str, help='Object type')
parser_delete.add_argument('key', type=str, help='Object identifier')
parser_post = subparsers.add_parser('create', help='Create an object')
parser_post.add_argument('type', type=str, help='Object type')
parser_post.add_argument('file', type=argparse.FileType('r'), help='Input file')
parser_put = subparsers.add_parser('update', help='Update an object')
parser_put.add_argument('type', type=str, help='Object type')
parser_put.add_argument('key', type=str, help='Object identifier')
parser_put.add_argument('file', type=argparse.FileType('r'), help='Input file')
parser_edit = subparsers.add_parser('edit', help='Edit an object')
parser_edit.add_argument('type', type=str, help='Object type')
parser_edit.add_argument('key', type=str, help='Object identifier')
args = parser.parse_args()
globals()[args.action](args)