OracleAction.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  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. # https://docs.cloud.oracle.com/en-us/iaas/tools/public_ip_ranges.json
  7. # config/defaults.json
  8. # {
  9. # "compartmentId": "ocid1.tenancy...",
  10. # "userId": "ocid1.user...",
  11. # "URL": "https://iaas.xxx.oraclecloud.com/20160918/",
  12. # "certFinger": "ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff",
  13. # "certKey": "-----BEGIN RSA PRIVATE KEY-----\n...\n-----END RSA PRIVATE KEY-----"
  14. # }
  15. # create/defaults.json
  16. # {
  17. # "shape": "VM.Standard.E2.1.Micro",
  18. # "availabilityDomain": "xx:XX",
  19. # "subnetId": "ocid1.subnet...",
  20. # "imageId": "ocid1.image...",
  21. # "user_data": "BASE64...",
  22. # "ssh_authorized_keys": "ssh-rsa ...",
  23. # }
  24. import hashlib
  25. import datetime
  26. import base64
  27. import json
  28. import time
  29. import rsa
  30. from urllib import request, error, parse
  31. class oracle:
  32. @staticmethod
  33. def http(url, method, headers=None, data=None, coding='utf-8'):
  34. if not headers:
  35. headers = {}
  36. if data is not None:
  37. if isinstance(data, (dict, list)):
  38. data = json.dumps(data)
  39. if 'content-length' not in [str(item).lower() for item in list(headers.keys())]:
  40. headers['Content-Length'] = str(len(data))
  41. data = str(data).encode(coding)
  42. url_obj = request.Request(url, method=method, data=data, headers=headers)
  43. try:
  44. res_obj = request.urlopen(url_obj)
  45. except error.HTTPError as err:
  46. res_obj = err
  47. return res_obj
  48. @staticmethod
  49. def header(keyID, privateKey, reqURL, reqMethod, body=None, algorithm="rsa-sha256"):
  50. sign_list = []
  51. url_parse = parse.urlparse(reqURL)
  52. _header_field = ["(request-target)", "date", "host"]
  53. _header = {
  54. 'host': str(url_parse.netloc),
  55. 'user-agent': 'oracle-api/1.0',
  56. 'date': str(datetime.datetime.utcnow().strftime("%a, %d %h %Y %H:%M:%S GMT")),
  57. 'accept': '*/*',
  58. 'accept-encoding': '',
  59. }
  60. 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="/?=&~")))
  61. if body is not None:
  62. if isinstance(body, (dict, list)):
  63. _body = json.dumps(body)
  64. else:
  65. _body = body
  66. _header_field += ["content-length", "content-type", "x-content-sha256"]
  67. _header['content-type'] = 'application/json'
  68. _header['content-length'] = str(len(_body))
  69. _header['x-content-sha256'] = str(base64.b64encode(hashlib.sha256(_body.encode("utf-8")).digest()).decode("utf-8"))
  70. sign_list += [str("{}: {}").format(item, _header[item]) for item in _header_field if "target" not in item]
  71. _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")
  72. _header['authorization'] = str('Signature keyId="{}",algorithm="{}",signature="{}",headers="{}"').format(keyID, algorithm, _signature, str(" ").join(_header_field))
  73. return _header
  74. @staticmethod
  75. def load_Key(file, BIN=False, coding='utf-8'):
  76. fd = open(file, 'r', encoding=coding)
  77. data = fd.read()
  78. fd.close()
  79. return str(data).strip().encode(coding) if BIN else str(data).strip()
  80. @staticmethod
  81. def load_Config(file, coding='utf-8'):
  82. fd = open(file, 'r', encoding=coding)
  83. data = fd.read()
  84. fd.close()
  85. return json.loads(data, encoding=coding)
  86. @classmethod
  87. def api(cls, method, url, keyID, privateKey, data=None):
  88. method_allow = ["GET", "HEAD", "DELETE", "PUT", "POST"]
  89. method = str(method).strip().upper()
  90. if method not in method_allow:
  91. raise Exception(str("Method Not Allow [{}]").format(method))
  92. if len(str(keyID).split("/")) != 3:
  93. raise Exception(str('Invalid "keyID"'))
  94. if method in ["PUT", "POST"] and data is None:
  95. data = ""
  96. privateKey = privateKey if isinstance(privateKey, bytes) else str(privateKey).strip().encode("utf-8")
  97. headers = cls.header(keyID, privateKey, url, method, data)
  98. return cls.http(url, method, headers, data)
  99. class action:
  100. def __init__(self, apiDict, instancesId=None, configDict=None):
  101. self.apiDict = apiDict
  102. self.privateKey = self.apiDict["certKey"]
  103. self.apiKey = "/".join([self.apiDict["compartmentId"], self.apiDict["userId"], self.apiDict["certFinger"]])
  104. self.configDict = configDict
  105. self.instancesId = instancesId
  106. self.instancesDict = None
  107. self.VNIC = None
  108. self.PRIVATE = None
  109. def getPrivateIP(self):
  110. if not self.instancesId:
  111. print("Require instancesId.")
  112. exit(1)
  113. url = self.apiDict["URL"] + "vnicAttachments?instanceId=" + self.instancesId + "&compartmentId=" + self.apiDict["compartmentId"]
  114. response = oracle.api("GET", url, keyID=self.apiKey, privateKey=self.privateKey)
  115. response_vnic = json.loads(response.read().decode())
  116. if response_vnic:
  117. self.VNIC = response_vnic[0]
  118. if not self.VNIC:
  119. print("Not Found VNIC.")
  120. exit(1)
  121. url = self.apiDict["URL"] + "privateIps?vnicId=" + self.VNIC["vnicId"]
  122. response = oracle.api("GET", url, keyID=self.apiKey, privateKey=self.privateKey)
  123. response_private = json.loads(response.read().decode())
  124. if response_private:
  125. for privateIp in response_private:
  126. if privateIp["isPrimary"]:
  127. self.PRIVATE = response_private[0]
  128. break
  129. if not self.PRIVATE:
  130. print("Not Found Private IP Address.")
  131. exit(1)
  132. def getPublicIP(self):
  133. url = self.apiDict["URL"] + "publicIps/actions/getByPrivateIpId"
  134. BodyOne = json.dumps({"privateIpId": self.PRIVATE["id"]}, ensure_ascii=False)
  135. response = oracle.api("POST", url, keyID=self.apiKey, privateKey=self.privateKey, data=BodyOne)
  136. if response.code >= 200 and response.code < 400:
  137. response_public = json.loads(response.read().decode())
  138. return response_public
  139. elif response.code >= 400 and response.code < 500:
  140. return None
  141. else:
  142. print("Server Error. [%s]" % response.code)
  143. exit(1)
  144. def delPublicIPbyAddress(self):
  145. if not self.instancesId:
  146. print("Require Address.")
  147. exit(1)
  148. url = self.apiDict["URL"] + "publicIps/actions/getByIpAddress"
  149. BodyOne = json.dumps({"ipAddress": self.instancesId}, ensure_ascii=False)
  150. response = oracle.api("POST", url, keyID=self.apiKey, privateKey=self.privateKey, data=BodyOne)
  151. response_json = json.loads(response.read().decode())
  152. if "id" in response_json:
  153. self.delPublicIP(publicIp=response_json["id"])
  154. else:
  155. print(response_json)
  156. def delPublicIP(self, publicIp):
  157. url = self.apiDict["URL"] + "publicIps/" + publicIp
  158. oracle.api("DELETE", url, keyID=self.apiKey, privateKey=self.privateKey)
  159. def newPublicIP(self):
  160. bodyTwo = {
  161. "lifetime": "EPHEMERAL",
  162. "compartmentId": self.apiDict["compartmentId"],
  163. "privateIpId": self.PRIVATE["id"],
  164. }
  165. url = self.apiDict["URL"] + "publicIps"
  166. BodyTwo = json.dumps(bodyTwo, ensure_ascii=False)
  167. response = oracle.api("POST", url, keyID=self.apiKey, privateKey=self.privateKey, data=BodyTwo)
  168. NewPublic = json.loads(response.read().decode())
  169. print("PublicIP:", NewPublic["ipAddress"])
  170. return NewPublic
  171. def showPublicIP(self, showLog=True):
  172. self.getPrivateIP()
  173. PUBLIC = self.getPublicIP()
  174. publicIp = "NULL"
  175. if PUBLIC:
  176. publicIp = PUBLIC["ipAddress"]
  177. if showLog:
  178. print("PublicIP: %s" % publicIp)
  179. return PUBLIC
  180. def changePubilcIP(self):
  181. self.getPrivateIP()
  182. PUBLIC = self.getPublicIP()
  183. publicIp = "NULL"
  184. if PUBLIC:
  185. publicIp = PUBLIC["ipAddress"]
  186. self.delPublicIP(PUBLIC["id"])
  187. print("PublicIP[*]: %s" % publicIp)
  188. PUBLIC = self.newPublicIP()
  189. return PUBLIC
  190. def delete(self):
  191. if not self.instancesId:
  192. print("Require instancesId.")
  193. exit(1)
  194. url = self.apiDict["URL"] + "instances/" + self.instancesId + "?preserveBootVolume=false"
  195. response = oracle.api("DELETE", url, keyID=self.apiKey, privateKey=self.privateKey, data=None)
  196. response_json = {}
  197. response_json["status_code"] = str(response.code)
  198. response_json["data"] = response.read().decode()
  199. if response_json["status_code"] == "204":
  200. print("Delete success! ")
  201. else:
  202. print(json.dumps(response_json, indent=4))
  203. def reboot(self):
  204. if not self.instancesId:
  205. print("Require instancesId.")
  206. exit(1)
  207. url = self.apiDict["URL"] + "instances/" + self.instancesId + "?action=RESET"
  208. response = oracle.api("POST", url, keyID=self.apiKey, privateKey=self.privateKey, data=None)
  209. response_json = json.loads(response.read().decode())
  210. response_json["status_code"] = str(response.code)
  211. if response_json["status_code"] == "200":
  212. itemItem = {}
  213. itemItem["displayName"] = response_json["displayName"]
  214. itemItem["shape"] = response_json["shape"]
  215. itemItem["lifecycleState"] = response_json["lifecycleState"]
  216. itemItem["id"] = response_json["id"]
  217. itemItem["timeCreated"] = response_json["timeCreated"]
  218. itemItem["actionStatus"] = "SUCCESS"
  219. else:
  220. itemItem = response_json
  221. print(json.dumps(itemItem, indent=4))
  222. def rename(self, newName, DisableMonitoring=True):
  223. if not self.instancesId:
  224. print("Require instancesId.")
  225. exit(1)
  226. setName = str(newName).strip()
  227. if not setName:
  228. print("Name Invalid.")
  229. exit(1)
  230. body = {"displayName": setName, "agentConfig": {"isMonitoringDisabled": DisableMonitoring}}
  231. url = self.apiDict["URL"] + "instances/" + self.instancesId
  232. Body = json.dumps(body, ensure_ascii=False)
  233. response = oracle.api("PUT", url, keyID=self.apiKey, privateKey=self.privateKey, data=Body)
  234. response_json = json.loads(response.read().decode())
  235. response_json["status_code"] = str(response.code)
  236. print(json.dumps(response_json, indent=4))
  237. def getInstances(self):
  238. url = self.apiDict["URL"] + "instances?compartmentId=" + self.apiDict["compartmentId"]
  239. response = oracle.api("GET", url, keyID=self.apiKey, privateKey=self.privateKey)
  240. response_json = json.loads(response.read().decode())
  241. InstancesItem = []
  242. for item in response_json:
  243. itemItem = {}
  244. itemItem["displayName"] = item["displayName"]
  245. itemItem["shape"] = item["shape"]
  246. itemItem["lifecycleState"] = item["lifecycleState"]
  247. itemItem["id"] = item["id"]
  248. itemItem["timeCreated"] = item["timeCreated"]
  249. InstancesItem.append(itemItem)
  250. return InstancesItem
  251. def createInstancesPre(self, Name=None):
  252. self.instancesDict = {
  253. 'displayName': str(str(self.configDict["availabilityDomain"]).split(":", 1)[-1].split("-")[1]),
  254. 'shape': self.configDict["shape"],
  255. 'compartmentId': self.apiDict["compartmentId"],
  256. 'availabilityDomain': self.configDict["availabilityDomain"],
  257. 'sourceDetails': {
  258. 'sourceType': 'image',
  259. 'imageId': self.configDict['imageId'],
  260. },
  261. 'createVnicDetails': {
  262. 'subnetId': self.configDict['subnetId'],
  263. 'assignPublicIp': True
  264. },
  265. 'metadata': {
  266. 'user_data': self.configDict['user_data'],
  267. 'ssh_authorized_keys': self.configDict['ssh_authorized_keys'],
  268. },
  269. 'agentConfig': {
  270. 'isMonitoringDisabled': False,
  271. 'isManagementDisabled': False
  272. },
  273. }
  274. if Name and str(Name).strip():
  275. self.instancesDict['displayName'] = str(Name).strip()
  276. def createInstances(self, Name=None, Full=True, WaitResource=True):
  277. url = self.apiDict["URL"] + "instances"
  278. if not self.instancesDict or Name is not None:
  279. self.createInstancesPre(Name=Name)
  280. body = json.dumps(self.instancesDict, ensure_ascii=False)
  281. while True:
  282. FLAG = False
  283. try:
  284. try:
  285. response = oracle.api("POST", url, keyID=self.apiKey, privateKey=self.privateKey, data=body)
  286. response_json = json.loads(response.read().decode())
  287. response_json["status_code"] = str(response.code)
  288. except Exception as e:
  289. print(e)
  290. response_json = {"code": "InternalError", "message": "Timeout.", "status_code": "555"}
  291. if str(response_json["status_code"]).startswith("4"):
  292. FLAG = True
  293. if str(response_json["status_code"]) == "401":
  294. response_json["message"] = "Not Authenticated."
  295. elif str(response_json["status_code"]) == "400":
  296. if str(response_json["code"]) == "LimitExceeded":
  297. response_json["message"] = "Limit Exceeded."
  298. if str(response_json["code"]) == "QuotaExceeded":
  299. response_json["message"] = "Quota Exceeded."
  300. elif str(response_json["status_code"]) == "429":
  301. FLAG = False
  302. elif str(response_json["status_code"]) == "404":
  303. if WaitResource and str(response_json["code"]) == "NotAuthorizedOrNotFound":
  304. FLAG = False
  305. if int(response_json["status_code"]) < 300:
  306. vm_ocid = str(str(response_json["id"]).split(".")[-1])
  307. print(str("{} [{}] {}").format(time.strftime("[%Y/%m/%d %H:%M:%S]", time.localtime()), response_json["status_code"], str(vm_ocid[:5] + "..." + vm_ocid[-7:])))
  308. else:
  309. print(str("{} [{}] {}").format(time.strftime("[%Y/%m/%d %H:%M:%S]", time.localtime()), response_json["status_code"], response_json["message"]))
  310. if Full is False and str(response_json["status_code"]) == "200":
  311. FLAG = True
  312. if not FLAG:
  313. if str(response_json["status_code"]) == "429":
  314. time.sleep(60)
  315. elif str(response_json["status_code"]) == "404":
  316. time.sleep(30)
  317. else:
  318. time.sleep(5)
  319. except Exception as e:
  320. FLAG = True
  321. print(e)
  322. if FLAG:
  323. break
  324. if __name__ == "__main__":
  325. def Exit(code=0, msg=None):
  326. if msg:
  327. print(msg)
  328. exit(code)
  329. import argparse
  330. parser = argparse.ArgumentParser()
  331. parser.add_argument('-c', type=str, default="", help="Config Path")
  332. parser.add_argument('-i', type=str, default="", help="Instances Id or Instances Config Path")
  333. parser.add_argument('-n', type=str, default="", help="New Instances Name")
  334. parser.add_argument('-p', type=str, default="", help="IP Address Prefix")
  335. parser.add_argument('-a', type=str, default="", help="Action [show, change, rename, create, reboot, delete, deladdr, target, list, listaddr]")
  336. args = parser.parse_args()
  337. configPath = str(args.c).strip()
  338. configAction = str(args.a).strip().lower()
  339. configInstancesId = str(args.i).strip()
  340. configInstancesName = str(args.n).strip()
  341. configAddress = str(args.p).strip()
  342. configActionList = ["show", "change", "rename", "create", "reboot", "delete", "deladdr", "target", "list", "listaddr"]
  343. if not configPath:
  344. Exit(1, "Require Config Path.")
  345. if not configAction or configAction not in configActionList:
  346. Exit(1, "Invalid Action.")
  347. if not configAction.startswith("list") and not configInstancesId:
  348. Exit(1, "Require Instances Id or Instances Config Path.")
  349. if configAction == "loop" and not configAddress:
  350. configAction = "change"
  351. if configAction == "show":
  352. Action = action(apiDict=oracle.load_Config(configPath), instancesId=configInstancesId)
  353. Action.showPublicIP()
  354. elif configAction == "change":
  355. Action = action(apiDict=oracle.load_Config(configPath), instancesId=configInstancesId)
  356. Action.changePubilcIP()
  357. elif configAction == "rename":
  358. if not configInstancesName:
  359. Exit(1, "Require Instances Name.")
  360. Action = action(apiDict=oracle.load_Config(configPath), instancesId=configInstancesId)
  361. Action.rename(configInstancesName)
  362. elif configAction == "reboot":
  363. Action = action(apiDict=oracle.load_Config(configPath), instancesId=configInstancesId)
  364. Action.reboot()
  365. elif configAction == "delete":
  366. Action = action(apiDict=oracle.load_Config(configPath), instancesId=configInstancesId)
  367. Action.delete()
  368. elif configAction == "deladdr":
  369. Action = action(apiDict=oracle.load_Config(configPath), instancesId=configInstancesId)
  370. Action.delPublicIPbyAddress()
  371. elif configAction == "create":
  372. if not configInstancesName:
  373. configInstancesName = None
  374. else:
  375. configInstancesName = str(configInstancesName).strip()
  376. Action = action(apiDict=oracle.load_Config(configPath), configDict=oracle.load_Config(configInstancesId))
  377. Action.createInstances(configInstancesName)
  378. elif configAction == "target":
  379. Action = action(apiDict=oracle.load_Config(configPath), instancesId=configInstancesId)
  380. while True:
  381. NewPublic = Action.changePubilcIP()
  382. if str(NewPublic["ipAddress"]).startswith(configAddress):
  383. break
  384. else:
  385. del NewPublic
  386. time.sleep(3)
  387. elif configAction == "list":
  388. Action = action(apiDict=oracle.load_Config(configPath))
  389. Item = Action.getInstances()
  390. print(json.dumps(Item, indent=4))
  391. elif configAction == "listaddr":
  392. Action = action(apiDict=oracle.load_Config(configPath))
  393. Item = Action.getInstances()
  394. ItemWithAddress = []
  395. try:
  396. for item in Item.copy():
  397. if item["lifecycleState"] == "TERMINATED":
  398. continue
  399. Action.instancesId = item["id"]
  400. Action.PRIVATE = None
  401. Action.VNIC = None
  402. Action.getPrivateIP()
  403. PUBLIC = Action.getPublicIP()
  404. item["ipAddress"] = "NULL"
  405. if PUBLIC:
  406. item["ipAddress"] = PUBLIC["ipAddress"]
  407. ItemWithAddress.append(item)
  408. except:
  409. print(json.dumps(Item, indent=4))
  410. Exit(0)
  411. print(json.dumps(ItemWithAddress, indent=4))
  412. Exit(0)