OracleAction.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. #!/usr/bin/env python3
  2. # -*- encoding: utf-8 -*-
  3. # Author: MoeClub.org
  4. # pip3 install rsa
  5. # python3 OracleAction.py -c "config/defaults.json" -i "ocid1.instance...|create/defaults.json" -a "<action>" -n "name"
  6. # config/defaults.json
  7. # {
  8. # "compartmentId": "ocid1.tenancy...",
  9. # "userId": "ocid1.user...",
  10. # "URL": "https://iaas.xxx.oraclecloud.com/20160918/",
  11. # "certFinger": "ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff",
  12. # "certKey": "-----BEGIN RSA PRIVATE KEY-----\n...\n-----END RSA PRIVATE KEY-----"
  13. # }
  14. # create/defaults.json
  15. # {
  16. # "shape": "VM.Standard.E2.1.Micro",
  17. # "availabilityDomain": "xx:XX",
  18. # "subnetId": "ocid1.subnet...",
  19. # "imageId": "BASE64...",
  20. # "ssh_authorized_keys": "ssh-rsa ...",
  21. # }
  22. import hashlib
  23. import datetime
  24. import base64
  25. import json
  26. import time
  27. import rsa
  28. from urllib import request, error, parse
  29. class oracle:
  30. @staticmethod
  31. def http(url, method, headers=None, data=None, coding='utf-8'):
  32. if not headers:
  33. headers = {}
  34. if data is not None:
  35. if isinstance(data, (dict, list)):
  36. data = json.dumps(data)
  37. if 'content-length' not in [str(item).lower() for item in list(headers.keys())]:
  38. headers['Content-Length'] = str(len(data))
  39. data = str(data).encode(coding)
  40. url_obj = request.Request(url, method=method, data=data, headers=headers)
  41. try:
  42. res_obj = request.urlopen(url_obj)
  43. except error.HTTPError as err:
  44. res_obj = err
  45. return res_obj
  46. @staticmethod
  47. def header(keyID, privateKey, reqURL, reqMethod, body=None, algorithm="rsa-sha256"):
  48. sign_list = []
  49. url_parse = parse.urlparse(reqURL)
  50. _header_field = ["(request-target)", "date", "host"]
  51. _header = {
  52. 'host': str(url_parse.netloc),
  53. 'user-agent': 'oracle-api/1.0',
  54. 'date': str(datetime.datetime.utcnow().strftime("%a, %d %h %Y %H:%M:%S GMT")),
  55. 'accept': '*/*',
  56. 'accept-encoding': '',
  57. }
  58. sign_list.append(str("(request-target): {} {}").format(str(reqMethod).lower(), parse.quote_plus(str("{}{}").format(url_parse.path, str("?{}").format(url_parse.query) if url_parse.query else ""), safe="/?=&~")))
  59. if body is not None:
  60. if isinstance(body, (dict, list)):
  61. _body = json.dumps(body)
  62. else:
  63. _body = body
  64. _header_field += ["content-length", "content-type", "x-content-sha256"]
  65. _header['content-type'] = 'application/json'
  66. _header['content-length'] = str(len(_body))
  67. _header['x-content-sha256'] = str(base64.b64encode(hashlib.sha256(_body.encode("utf-8")).digest()).decode("utf-8"))
  68. sign_list += [str("{}: {}").format(item, _header[item]) for item in _header_field if "target" not in item]
  69. _signature = base64.b64encode(rsa.sign(str(str("\n").join(sign_list)).encode("utf-8"), rsa.PrivateKey.load_pkcs1(privateKey if isinstance(privateKey, bytes) else str(privateKey).strip().encode("utf-8")), str(algorithm).split("-", 1)[-1].upper().replace("SHA", "SHA-"))).decode("utf-8")
  70. _header['authorization'] = str('Signature keyId="{}",algorithm="{}",signature="{}",headers="{}"').format(keyID, algorithm, _signature, str(" ").join(_header_field))
  71. return _header
  72. @staticmethod
  73. def load_Key(file, BIN=False, coding='utf-8'):
  74. fd = open(file, 'r', encoding=coding)
  75. data = fd.read()
  76. fd.close()
  77. return str(data).strip().encode(coding) if BIN else str(data).strip()
  78. @staticmethod
  79. def load_Config(file, coding='utf-8'):
  80. fd = open(file, 'r', encoding=coding)
  81. data = fd.read()
  82. fd.close()
  83. return json.loads(data, encoding=coding)
  84. @classmethod
  85. def api(cls, method, url, keyID, privateKey, data=None):
  86. method_allow = ["GET", "HEAD", "DELETE", "PUT", "POST"]
  87. method = str(method).strip().upper()
  88. if method not in method_allow:
  89. raise Exception(str("Method Not Allow [{}]").format(method))
  90. if len(str(keyID).split("/")) != 3:
  91. raise Exception(str('Invalid "keyID"'))
  92. if method in ["PUT", "POST"] and data is None:
  93. data = ""
  94. privateKey = privateKey if isinstance(privateKey, bytes) else str(privateKey).strip().encode("utf-8")
  95. headers = cls.header(keyID, privateKey, url, method, data)
  96. return cls.http(url, method, headers, data)
  97. class action:
  98. def __init__(self, apiDict, instancesId=None, configDict=None):
  99. self.apiDict = apiDict
  100. self.privateKey = self.apiDict["certKey"]
  101. self.apiKey = "/".join([self.apiDict["compartmentId"], self.apiDict["userId"], self.apiDict["certFinger"]])
  102. self.configDict = configDict
  103. self.instancesId = instancesId
  104. self.instancesDict = None
  105. self.VNIC = None
  106. self.PRIVATE = None
  107. def getPrivateIP(self):
  108. if not self.instancesId:
  109. print("Require instancesId.")
  110. exit(1)
  111. url = self.apiDict["URL"] + "vnicAttachments?instanceId=" + self.instancesId + "&compartmentId=" + self.apiDict["compartmentId"]
  112. response = oracle.api("GET", url, keyID=self.apiKey, privateKey=self.privateKey)
  113. response_vnic = json.loads(response.read().decode())
  114. if response_vnic:
  115. self.VNIC = response_vnic[0]
  116. if not self.VNIC:
  117. print("Not Found VNIC.")
  118. exit(1)
  119. url = self.apiDict["URL"] + "privateIps?vnicId=" + self.VNIC["vnicId"]
  120. response = oracle.api("GET", url, keyID=self.apiKey, privateKey=self.privateKey)
  121. response_private = json.loads(response.read().decode())
  122. if response_private:
  123. for privateIp in response_private:
  124. if privateIp["isPrimary"]:
  125. self.PRIVATE = response_private[0]
  126. break
  127. if not self.PRIVATE:
  128. print("Not Found Private IP Address.")
  129. exit(1)
  130. def getPublicIP(self):
  131. url = self.apiDict["URL"] + "publicIps/actions/getByPrivateIpId"
  132. BodyOne = json.dumps({"privateIpId": self.PRIVATE["id"]}, ensure_ascii=False)
  133. response = oracle.api("POST", url, keyID=self.apiKey, privateKey=self.privateKey, data=BodyOne)
  134. if response.code >= 200 and response.code < 400:
  135. response_public = json.loads(response.read().decode())
  136. return response_public
  137. elif response.code >= 400 and response.code < 500:
  138. return None
  139. else:
  140. print("Server Error. [%s]" % response.code)
  141. exit(1)
  142. def delPublicIP(self, publicIp):
  143. url = self.apiDict["URL"] + "publicIps/" + publicIp
  144. oracle.api("DELETE", url, keyID=self.apiKey, privateKey=self.privateKey)
  145. def newPublicIP(self):
  146. bodyTwo = {
  147. "lifetime": "EPHEMERAL",
  148. "compartmentId": self.apiDict["compartmentId"],
  149. "privateIpId": self.PRIVATE["id"],
  150. }
  151. url = self.apiDict["URL"] + "publicIps"
  152. BodyTwo = json.dumps(bodyTwo, ensure_ascii=False)
  153. response = oracle.api("POST", url, keyID=self.apiKey, privateKey=self.privateKey, data=BodyTwo)
  154. NewPublic = json.loads(response.read().decode())
  155. print("PublicIP:", NewPublic["ipAddress"])
  156. return NewPublic
  157. def showPublicIP(self):
  158. self.getPrivateIP()
  159. PUBLIC = self.getPublicIP()
  160. publicIp = "NULL"
  161. if PUBLIC:
  162. publicIp = PUBLIC["ipAddress"]
  163. print("PublicIP: %s" % publicIp)
  164. return PUBLIC
  165. def changePubilcIP(self):
  166. self.getPrivateIP()
  167. PUBLIC = self.getPublicIP()
  168. publicIp = "NULL"
  169. if PUBLIC:
  170. publicIp = PUBLIC["ipAddress"]
  171. self.delPublicIP(PUBLIC["id"])
  172. print("PublicIP[*]: %s" % publicIp)
  173. PUBLIC = self.newPublicIP()
  174. return PUBLIC
  175. def rename(self, newName, DisableMonitoring=True):
  176. if not self.instancesId:
  177. print("Require instancesId.")
  178. exit(1)
  179. setName = str(newName).strip()
  180. if not setName:
  181. print("Name Invalid.")
  182. exit(1)
  183. body = {"displayName": setName, "agentConfig": {"isMonitoringDisabled": DisableMonitoring}}
  184. url = self.apiDict["URL"] + "instances/" + self.instancesId
  185. Body = json.dumps(body, ensure_ascii=False)
  186. response = oracle.api("PUT", url, keyID=self.apiKey, privateKey=self.privateKey, data=Body)
  187. response_json = json.loads(response.read().decode())
  188. response_json["status_code"] = str(response.code)
  189. print(json.dumps(response_json, indent=4))
  190. def createInstancesPre(self, Name=None):
  191. self.instancesDict = {
  192. 'displayName': str(str(self.configDict["availabilityDomain"]).split(":", 1)[-1].split("-")[1]),
  193. 'shape': self.configDict["shape"],
  194. 'compartmentId': self.configDict["compartmentId"],
  195. 'availabilityDomain': self.configDict["availabilityDomain"],
  196. 'sourceDetails': {
  197. 'sourceType': 'image',
  198. 'imageId': self.configDict['imageId'],
  199. },
  200. 'createVnicDetails': {
  201. 'subnetId': self.configDict['subnetId'],
  202. 'assignPublicIp': True
  203. },
  204. 'metadata': {
  205. 'user_data': self.configDict['user_data'],
  206. 'ssh_authorized_keys': self.configDict['ssh_authorized_keys'],
  207. },
  208. 'agentConfig': {
  209. 'isMonitoringDisabled': False,
  210. 'isManagementDisabled': False
  211. },
  212. }
  213. if Name and str(Name).strip():
  214. self.instancesDict['displayName'] = str(Name).strip()
  215. def createInstances(self, Name=None, Full=True, WaitResource=True):
  216. url = self.apiDict["URL"] + "instances"
  217. if not self.instancesDict or Name is not None:
  218. self.createInstancesPre(Name=Name)
  219. body = json.dumps(self.instancesDict, ensure_ascii=False)
  220. while True:
  221. FLAG = False
  222. try:
  223. try:
  224. response = oracle.api("POST", url, keyID=self.apiKey, privateKey=self.privateKey, data=body)
  225. response_json = json.loads(response.read().decode())
  226. response_json["status_code"] = str(response.code)
  227. except Exception as e:
  228. print(e)
  229. response_json = {"code": "InternalError", "message": "Timeout.", "status_code": "555"}
  230. if str(response_json["status_code"]).startswith("4"):
  231. FLAG = True
  232. if str(response_json["status_code"]) == "401":
  233. response_json["message"] = "Not Authenticated."
  234. elif str(response_json["status_code"]) == "400":
  235. if str(response_json["code"]) == "LimitExceeded":
  236. response_json["message"] = "Limit Exceeded."
  237. if str(response_json["code"]) == "QuotaExceeded":
  238. response_json["message"] = "Quota Exceeded."
  239. elif str(response_json["status_code"]) == "429":
  240. FLAG = False
  241. elif str(response_json["status_code"]) == "404":
  242. if WaitResource and str(response_json["code"]) == "NotAuthorizedOrNotFound":
  243. FLAG = False
  244. if int(response_json["status_code"]) < 300:
  245. vm_ocid = str(str(response_json["id"]).split(".")[-1])
  246. print(str("{} [{}] {}").format(time.strftime("[%Y/%m/%d %H:%M:%S]", time.localtime()), response_json["status_code"], str(vm_ocid[:5] + "..." + vm_ocid[-7:])))
  247. else:
  248. print(str("{} [{}] {}").format(time.strftime("[%Y/%m/%d %H:%M:%S]", time.localtime()), response_json["status_code"], response_json["message"]))
  249. if Full is False and str(response_json["status_code"]) == "200":
  250. FLAG = True
  251. if not FLAG:
  252. if str(response_json["status_code"]) == "429":
  253. time.sleep(60)
  254. elif str(response_json["status_code"]) == "404":
  255. time.sleep(30)
  256. else:
  257. time.sleep(5)
  258. except Exception as e:
  259. FLAG = True
  260. print(e)
  261. if FLAG:
  262. break
  263. if __name__ == "__main__":
  264. def Exit(code=0, msg=None):
  265. if msg:
  266. print(msg)
  267. exit(code)
  268. import argparse
  269. parser = argparse.ArgumentParser()
  270. parser.add_argument('-c', type=str, default="", help="Config Path")
  271. parser.add_argument('-i', type=str, default="", help="Instances Id or Instances Config Path")
  272. parser.add_argument('-n', type=str, default="", help="New Instances Name")
  273. parser.add_argument('-a', type=str, default="", help="Action [show, change, rename, create]")
  274. args = parser.parse_args()
  275. configPath = str(args.c).strip()
  276. configAction = str(args.a).strip().lower()
  277. configInstancesId = str(args.i).strip()
  278. configInstancesName = str(args.n).strip()
  279. configActionList = ["show", "change", "rename", "create"]
  280. if not configPath:
  281. Exit(1, "Require Config Path.")
  282. if not configAction or configAction not in configActionList:
  283. Exit(1, "Invalid Action.")
  284. if not configInstancesId:
  285. Exit(1, "Require Instances Id or Instances Config Path.")
  286. if configAction == "show":
  287. Action = action(apiDict=oracle.load_Config(configPath), instancesId=configInstancesId)
  288. Action.showPublicIP()
  289. elif configAction == "change":
  290. Action = action(apiDict=oracle.load_Config(configPath), instancesId=configInstancesId)
  291. Action.changePubilcIP()
  292. elif configAction == "rename":
  293. if not configInstancesName:
  294. Exit(1, "Require Instances Name.")
  295. Action = action(apiDict=oracle.load_Config(configPath), instancesId=configInstancesId)
  296. Action.rename(configInstancesName)
  297. elif configAction == "create":
  298. if not configInstancesName:
  299. configInstancesName = None
  300. else:
  301. configInstancesName = str(configInstancesName).strip()
  302. Action = action(apiDict=oracle.load_Config(configPath), configDict=oracle.load_Config(configInstancesId))
  303. Action.createInstances(configInstancesName)
  304. Exit(0)