OracleAction.py 17 KB

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