diff --git a/template/register_instance2-6.py b/template/register_instance2-6.py new file mode 100644 index 0000000..7407b58 --- /dev/null +++ b/template/register_instance2-6.py @@ -0,0 +1,64 @@ +# Python 示例 +# yum install -y gcc +# pip3 install requests drf-httpsig -i https://mirrors.aliyun.com/pypi/simple/ +import requests +import datetime +from httpsig.requests_auth import HTTPSignatureAuth +from subprocess import getoutput +import sys,os,json + +if os.path.exists("/tmp/.instance.json"): + exit() + +def get_host_info(): + try: + username = sys.argv[1] + password = sys.argv[2] + except: + print("Usage: python3 register_instance2-6.py ") + host_ip = getoutput( + """ip -4 a show dev ens33 | awk '/inet/{print $2}' | awk 'BEGIN{FS="/"}{print $1}'""") + hostname = f"""{host_ip}-{getoutput('hostname')}""" + return (host_ip, hostname, username, password) + +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 get_user_info(jms_url, auth): + url = jms_url + '/api/v1/assets/hosts/' + 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) + } + info = get_host_info() + data = { + "name": info[1], + "address": info[0], + "platform": "1", + "accounts": [ + { + "username": info[2], + "secret_type": "password", + "secret": info[3] + } + ], + "is_active": True + } + response = requests.post(url, auth=auth, json=data, headers=headers) + with open('/tmp/.instance.json', 'w') as f: + json.dump(response.json(), f, ensure_ascii=False, indent="\t") + + +if __name__ == '__main__': + jms_url = 'http://192.168.75.250' + KeyID = 'ed06b13e-5eb2-4e50-b472-dad9008ec40a' + SecretID = 'tpP2wfDXWzYbXSlgLLYJkFIA7cuI8tAr9Msi' + auth = get_auth(KeyID, SecretID) + get_user_info(jms_url, auth) +