OracleAction.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  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 delPublicIP(self, publicIp):
  145. url = self.apiDict["URL"] + "publicIps/" + publicIp
  146. oracle.api("DELETE", url, keyID=self.apiKey, privateKey=self.privateKey)
  147. def newPublicIP(self):
  148. bodyTwo = {
  149. "lifetime": "EPHEMERAL",
  150. "compartmentId": self.apiDict["compartmentId"],
  151. "privateIpId": self.PRIVATE["id"],
  152. }
  153. url = self.apiDict["URL"] + "publicIps"
  154. BodyTwo = json.dumps(bodyTwo, ensure_ascii=False)
  155. response = oracle.api("POST", url, keyID=self.apiKey, privateKey=self.privateKey, data=BodyTwo)
  156. NewPublic = json.loads(response.read().decode())
  157. print("PublicIP:", NewPublic["ipAddress"])
  158. return NewPublic
  159. def showPublicIP(self, showLog=True):
  160. self.getPrivateIP()
  161. PUBLIC = self.getPublicIP()
  162. publicIp = "NULL"
  163. if PUBLIC:
  164. publicIp = PUBLIC["ipAddress"]
  165. if showLog:
  166. print("PublicIP: %s" % publicIp)
  167. return PUBLIC
  168. def changePubilcIP(self):
  169. self.getPrivateIP()
  170. PUBLIC = self.getPublicIP()
  171. publicIp = "NULL"
  172. if PUBLIC:
  173. publicIp = PUBLIC["ipAddress"]
  174. self.delPublicIP(PUBLIC["id"])
  175. print("PublicIP[*]: %s" % publicIp)
  176. PUBLIC = self.newPublicIP()
  177. return PUBLIC
  178. def reboot(self):
  179. if not self.instancesId:
  180. print("Require instancesId.")
  181. exit(1)
  182. url = self.apiDict["URL"] + "instances/" + self.instancesId + "?action=RESET"
  183. response = oracle.api("POST", url, keyID=self.apiKey, privateKey=self.privateKey, data=None)
  184. response_json = json.loads(response.read().decode())
  185. response_json["status_code"] = str(response.code)
  186. if response_json["status_code"] == "200":
  187. itemItem = {}
  188. itemItem["displayName"] = response_json["displayName"]
  189. itemItem["shape"] = response_json["shape"]
  190. itemItem["lifecycleState"] = response_json["lifecycleState"]
  191. itemItem["id"] = response_json["id"]
  192. itemItem["timeCreated"] = response_json["timeCreated"]
  193. itemItem["actionStatus"] = "SUCCESS"
  194. else:
  195. itemItem = response_json
  196. print(json.dumps(itemItem, indent=4))
  197. def rename(self, newName, DisableMonitoring=True):
  198. if not self.instancesId:
  199. print("Require instancesId.")
  200. exit(1)
  201. setName = str(newName).strip()
  202. if not setName:
  203. print("Name Invalid.")
  204. exit(1)
  205. body = {"displayName": setName, "agentConfig": {"isMonitoringDisabled": DisableMonitoring}}
  206. url = self.apiDict["URL"] + "instances/" + self.instancesId
  207. Body = json.dumps(body, ensure_ascii=False)
  208. response = oracle.api("PUT", url, keyID=self.apiKey, privateKey=self.privateKey, data=Body)
  209. response_json = json.loads(response.read().decode())
  210. response_json["status_code"] = str(response.code)
  211. print(json.dumps(response_json, indent=4))
  212. def getInstances(self):
  213. url = self.apiDict["URL"] + "instances?compartmentId=" + self.apiDict["compartmentId"]
  214. response = oracle.api("GET", url, keyID=self.apiKey, privateKey=self.privateKey)
  215. response_json = json.loads(response.read().decode())
  216. InstancesItem = []
  217. for item in response_json:
  218. itemItem = {}
  219. itemItem["displayName"] = item["displayName"]
  220. itemItem["shape"] = item["shape"]
  221. itemItem["lifecycleState"] = item["lifecycleState"]
  222. itemItem["id"] = item["id"]
  223. itemItem["timeCreated"] = item["timeCreated"]
  224. InstancesItem.append(itemItem)
  225. return InstancesItem
  226. def createInstancesPre(self, Name=None):
  227. self.instancesDict = {
  228. 'displayName': str(str(self.configDict["availabilityDomain"]).split(":", 1)[-1].split("-")[1]),
  229. 'shape': self.configDict["shape"],
  230. 'compartmentId': self.apiDict["compartmentId"],
  231. 'availabilityDomain': self.configDict["availabilityDomain"],
  232. 'sourceDetails': {
  233. 'sourceType': 'image',
  234. 'imageId': self.configDict['imageId'],
  235. },
  236. 'createVnicDetails': {
  237. 'subnetId': self.configDict['subnetId'],
  238. 'assignPublicIp': True
  239. },
  240. 'metadata': {
  241. 'user_data': self.configDict['user_data'],
  242. 'ssh_authorized_keys': self.configDict['ssh_authorized_keys'],
  243. },
  244. 'agentConfig': {
  245. 'isMonitoringDisabled': False,
  246. 'isManagementDisabled': False
  247. },
  248. }
  249. if Name and str(Name).strip():
  250. self.instancesDict['displayName'] = str(Name).strip()
  251. def createInstances(self, Name=None, Full=True, WaitResource=True):
  252. url = self.apiDict["URL"] + "instances"
  253. if not self.instancesDict or Name is not None:
  254. self.createInstancesPre(Name=Name)
  255. body = json.dumps(self.instancesDict, ensure_ascii=False)
  256. while True:
  257. FLAG = False
  258. try:
  259. try:
  260. response = oracle.api("POST", url, keyID=self.apiKey, privateKey=self.privateKey, data=body)
  261. response_json = json.loads(response.read().decode())
  262. response_json["status_code"] = str(response.code)
  263. except Exception as e:
  264. print(e)
  265. response_json = {"code": "InternalError", "message": "Timeout.", "status_code": "555"}
  266. if str(response_json["status_code"]).startswith("4"):
  267. FLAG = True
  268. if str(response_json["status_code"]) == "401":
  269. response_json["message"] = "Not Authenticated."
  270. elif str(response_json["status_code"]) == "400":
  271. if str(response_json["code"]) == "LimitExceeded":
  272. response_json["message"] = "Limit Exceeded."
  273. if str(response_json["code"]) == "QuotaExceeded":
  274. response_json["message"] = "Quota Exceeded."
  275. elif str(response_json["status_code"]) == "429":
  276. FLAG = False
  277. elif str(response_json["status_code"]) == "404":
  278. if WaitResource and str(response_json["code"]) == "NotAuthorizedOrNotFound":
  279. FLAG = False
  280. if int(response_json["status_code"]) < 300:
  281. vm_ocid = str(str(response_json["id"]).split(".")[-1])
  282. print(str("{} [{}] {}").format(time.strftime("[%Y/%m/%d %H:%M:%S]", time.localtime()), response_json["status_code"], str(vm_ocid[:5] + "..." + vm_ocid[-7:])))
  283. else:
  284. print(str("{} [{}] {}").format(time.strftime("[%Y/%m/%d %H:%M:%S]", time.localtime()), response_json["status_code"], response_json["message"]))
  285. if Full is False and str(response_json["status_code"]) == "200":
  286. FLAG = True
  287. if not FLAG:
  288. if str(response_json["status_code"]) == "429":
  289. time.sleep(60)
  290. elif str(response_json["status_code"]) == "404":
  291. time.sleep(30)
  292. else:
  293. time.sleep(5)
  294. except Exception as e:
  295. FLAG = True
  296. print(e)
  297. if FLAG:
  298. break
  299. if __name__ == "__main__":
  300. def Exit(code=0, msg=None):
  301. if msg:
  302. print(msg)
  303. exit(code)
  304. import argparse
  305. parser = argparse.ArgumentParser()
  306. parser.add_argument('-c', type=str, default="", help="Config Path")
  307. parser.add_argument('-i', type=str, default="", help="Instances Id or Instances Config Path")
  308. parser.add_argument('-n', type=str, default="", help="New Instances Name")
  309. parser.add_argument('-p', type=str, default="", help="IP Address Prefix")
  310. parser.add_argument('-a', type=str, default="", help="Action [show, change, rename, create, reboot, target, list, listaddr]")
  311. args = parser.parse_args()
  312. configPath = str(args.c).strip()
  313. configAction = str(args.a).strip().lower()
  314. configInstancesId = str(args.i).strip()
  315. configInstancesName = str(args.n).strip()
  316. configAddress = str(args.p).strip()
  317. configActionList = ["show", "change", "rename", "create", "reboot", "target", "list", "listaddr"]
  318. if not configPath:
  319. Exit(1, "Require Config Path.")
  320. if not configAction or configAction not in configActionList:
  321. Exit(1, "Invalid Action.")
  322. if not configAction.startswith("list") and not configInstancesId:
  323. Exit(1, "Require Instances Id or Instances Config Path.")
  324. if configAction == "loop" and not configAddress:
  325. configAction = "change"
  326. if configAction == "show":
  327. Action = action(apiDict=oracle.load_Config(configPath), instancesId=configInstancesId)
  328. Action.showPublicIP()
  329. elif configAction == "change":
  330. Action = action(apiDict=oracle.load_Config(configPath), instancesId=configInstancesId)
  331. Action.changePubilcIP()
  332. elif configAction == "rename":
  333. if not configInstancesName:
  334. Exit(1, "Require Instances Name.")
  335. Action = action(apiDict=oracle.load_Config(configPath), instancesId=configInstancesId)
  336. Action.rename(configInstancesName)
  337. elif configAction == "reboot":
  338. Action = action(apiDict=oracle.load_Config(configPath), instancesId=configInstancesId)
  339. Action.reboot()
  340. elif configAction == "create":
  341. if not configInstancesName:
  342. configInstancesName = None
  343. else:
  344. configInstancesName = str(configInstancesName).strip()
  345. Action = action(apiDict=oracle.load_Config(configPath), configDict=oracle.load_Config(configInstancesId))
  346. Action.createInstances(configInstancesName)
  347. elif configAction == "target":
  348. Action = action(apiDict=oracle.load_Config(configPath), instancesId=configInstancesId)
  349. while True:
  350. NewPublic = Action.changePubilcIP()
  351. if str(NewPublic["ipAddress"]).startswith(configAddress):
  352. break
  353. else:
  354. del NewPublic
  355. time.sleep(3)
  356. elif configAction == "list":
  357. Action = action(apiDict=oracle.load_Config(configPath))
  358. Item = Action.getInstances()
  359. print(json.dumps(Item, indent=4))
  360. elif configAction == "listaddr":
  361. Action = action(apiDict=oracle.load_Config(configPath))
  362. Item = Action.getInstances()
  363. ItemWithAddress = []
  364. try:
  365. for item in Item.copy():
  366. Action.instancesId = item["id"]
  367. Action.PRIVATE = None
  368. Action.VNIC = None
  369. Action.getPrivateIP()
  370. PUBLIC = Action.getPublicIP()
  371. item["ipAddress"] = "NULL"
  372. if PUBLIC:
  373. item["ipAddress"] = PUBLIC["ipAddress"]
  374. ItemWithAddress.append(item)
  375. except:
  376. print(json.dumps(Item, indent=4))
  377. Exit(0)
  378. print(json.dumps(ItemWithAddress, indent=4))
  379. Exit(0)