import subprocess import os,sys import json import requests import datetime from httpsig.requests_auth import HTTPSignatureAuth jms_url = 'http://192.168.96.239' nodes_id="ad851ca4-45cb-4d8a-9e0a-6e4e4fb6b6e1" admin_user_id="739037a2-0850-4b95-845d-c2e023e47f33" KeyID = '445b20ee-fcb5-4ad2-965e-3b6f2d6d658a' SecretID = 'd303d92d-5691-49db-a7fc-67b24cf09770' def get_auth(KeyID, SecretID): signature_headers = ['(request-target)', 'accept', 'date'] auth = HTTPSignatureAuth(key_id=KeyID, secret=SecretID, algorithm='hmac-sha256', headers=signature_headers) return auth def check_host(jms_url, auth, host_ip): url = jms_url + "/api/v1/assets/assets/" gmt_form = '%a, %d %b %Y %H:%M:%S GMT' headers = { 'Accept': 'application/json', 'X-JMS-ORG': '00000000-0000-0000-0000-000000000002', 'Date': datetime.datetime.utcnow().strftime(gmt_form) } result = requests.get( url, params={"ip": host_ip}, auth=auth, headers=headers) return bool(result.json()) def register_host(jms_url, auth, host_name, host_ip): if not check_host(jms_url, auth, host_ip): url = jms_url + "/api/v1/assets/assets/" gmt_form = '%a, %d %b %Y %H:%M:%S GMT' headers = { 'Accept': 'application/json', 'X-JMS-ORG': '00000000-0000-0000-0000-000000000002', 'Date': datetime.datetime.utcnow().strftime(gmt_form) } data = { "hostname": host_name, "ip": host_ip, "platform": "Linux", "protocol": "ssh", "port": 0, "nodes": nodes_id, "admin_user": admin_user_id, "is_active": True } result = requests.post(url, data=data, auth=auth, headers=headers) with open("/tmp/.jms_host_registered.json", "w") as f: json.dump(result.json(), f, indent=4, ensure_ascii=False) if __name__ == '__main__': if os.path.isfile('/tmp/.jms_host_registered.json'): exit(0) auth = get_auth(KeyID, SecretID) hostip = subprocess.getoutput('hostname -I') hostname = sys.argv[1] register_host(jms_url, auth, hostname, hostip)