Guest User

Untitled

a guest
Jan 3rd, 2018
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.84 KB | None | 0 0
  1. #
  2.  
  3. import requests, json, sys, re, time, warnings
  4.  
  5.  
  6. from datetime import datetime
  7.  
  8. warnings.filterwarnings("ignore")
  9.  
  10.  
  11.  
  12. #Function to get certificate from server
  13. def get_cert(ipaddress, port = 443):
  14. """
  15. Getting and building the SSL ceritificate.
  16. """
  17.  
  18. import os
  19. import ssl
  20. from sys import stdout
  21. filename = "cer-"+ipaddress+".cer"
  22. if os.path.isfile(filename):
  23. print "SSL Certificate exists!"
  24. pass
  25. else:
  26. print 'Getting SSL Certificate. Waiting for response.',
  27. stdout.flush()
  28. cert = ssl.get_server_certificate((ipaddress,port))
  29. text_file = open(filename, "w")
  30. text_file.writelines(cert)
  31. text_file.close()
  32. print "Response received."
  33.  
  34. return filename
  35.  
  36.  
  37.  
  38.  
  39. # Code to validate all correct parameters are passed in
  40. try:
  41. idrac_ip = sys.argv[1]
  42. idrac_username = sys.argv[2]
  43. idrac_password = sys.argv[3]
  44. firmware_image_location = sys.argv[4]
  45. file_image_name= sys.argv[5]
  46. Install_Option = sys.argv[6]
  47. cert = get_cert(idrac_ip)
  48. print cert
  49. except:
  50. print("\n- FAIL, you must pass in script name along with iDRAC IP / iDRAC username / iDRAC password / Image Path / Filename / Install Option. Example: \" script_name.py 192.168.0.120 root calvin c:\Python26 bios.exe NowAndReboot\"")
  51. sys.exit()
  52.  
  53. start_time=datetime.now()
  54.  
  55. # Code to convert install option to correct string due to case sensitivity in iDRAC.
  56. if Install_Option == "now":
  57. install_option = "Now"
  58. elif Install_Option == "nowandreboot":
  59. install_option = "NowAndReboot"
  60. elif Install_Option == "nextreboot":
  61. install_option = "NextReboot"
  62. else:
  63. install_option = Install_Option
  64.  
  65.  
  66. # Function to download the image payload to the iDRAC
  67.  
  68. def download_image_payload():
  69. print("\n- WARNING, downloading DUP payload to iDRAC\n")
  70. global Location
  71. global new_FW_version
  72. global dup_version
  73. req = requests.get('https://%s/redfish/v1/UpdateService/FirmwareInventory/' % (idrac_ip), auth=(idrac_username, idrac_password), verify=False,cert=cert)
  74. statusCode = req.status_code
  75. data = req.json()
  76. filename = file_image_name.lower()
  77. ImageLocation = firmware_image_location
  78. ImagePath = ImageLocation + "\\" + filename
  79. ETag = req.headers['ETag']
  80. url = 'https://%s/redfish/v1/UpdateService/FirmwareInventory' % (idrac_ip)
  81. files = {'file': (filename, open(ImagePath, 'rb'), 'multipart/form-data')}
  82. headers = {"if-match": ETag}
  83. response = requests.post(url, files=files, auth = (idrac_username, idrac_password), verify=False, headers=headers,cert=cert)
  84. d = response.__dict__
  85. s=str(d['_content'])
  86. if response.status_code == 201:
  87. print("\n- PASS: Command passed, 201 status code returned\n")
  88. z=re.search("\"Message\":.+?,",s).group().rstrip(",")
  89. z=re.sub('"',"",z)
  90. print("- %s" % z)
  91. else:
  92. print("\n- FAIL: Post command failed to download, error is %s" % response)
  93. print("\nMore details on status code error: %s " % d['_content'])
  94. sys.exit()
  95. d = response.__dict__
  96. z=re.search("Available.+?,",s).group()
  97. z = re.sub('[",]',"",z)
  98. new_FW_version = re.sub('Available','Installed',z)
  99. zz=z.find("-")
  100. zz=z.find("-",zz+1)
  101. dup_version = z[zz+1:]
  102. entry = "- FW file version is: %s" % dup_version; print(entry)
  103. Location = response.headers['Location']
  104.  
  105.  
  106. # Function to install the downloaded image payload and loop checking job status
  107.  
  108. def install_image_payload():
  109. global job_id
  110. print("\n- WARNING, installing downloaded firmware payload to device\n")
  111. url = 'https://%s/redfish/v1/UpdateService/Actions/Oem/DellUpdateService.Install' % (idrac_ip)
  112. InstallOption = install_option
  113. payload = "{\"SoftwareIdentityURIs\":[\"" + Location + "\"],\"InstallUpon\":\""+ InstallOption +"\"}"
  114. headers = {'content-type': 'application/json'}
  115. response = requests.post(url, data=payload, auth = (idrac_username, idrac_password), verify=False, headers=headers,cert=cert)
  116. d=str(response.__dict__)
  117. job_id_location = response.headers['Location']
  118. job_id = re.search("JID_.+",job_id_location).group()
  119. print("\n- PASS, %s job ID successfully created\n" % job_id)
  120.  
  121.  
  122.  
  123. # Function to check the new FW version installed
  124.  
  125. def check_new_FW_version():
  126. print("\n- WARNING, checking new firmware version installed for updated device\n")
  127. req = requests.get('https://%s/redfish/v1/UpdateService/FirmwareInventory/%s' % (idrac_ip, new_FW_version), auth=(idrac_username, idrac_password), verify=False,cert=cert)
  128. statusCode = req.status_code
  129. data = req.json()
  130. if dup_version == data[u'Version']:
  131. print("\n- PASS, New installed FW version is: %s" % data[u'Version'])
  132. else:
  133. print("\n- FAIL, New installed FW incorrect, error is: %s" % data)
  134. sys.exit()
  135.  
  136. # Function to check the job status for host reboot needed
  137.  
  138. def check_job_status_host_reboot():
  139. time.sleep(15)
  140. while True:
  141. req = requests.get('https://%s/redfish/v1/TaskService/Tasks/%s' % (idrac_ip, job_id), auth=(idrac_username, idrac_password), verify=False,cert=cert)
  142. statusCode = req.status_code
  143. data = req.json()
  144. message_string=data[u"Messages"]
  145. current_time=(datetime.now()-start_time)
  146. if statusCode == 202 or statusCode == 200:
  147. print("\n- Query job ID command passed\n")
  148. time.sleep(10)
  149. else:
  150. print("Query job ID command failed, error code is: %s" % statusCode)
  151. sys.exit()
  152. if "failed" in data[u"Messages"] or "completed with errors" in data[u"Messages"]:
  153. print("- FAIL: Job failed, current message is: %s" % data[u"Messages"])
  154. sys.exit()
  155. elif data[u"TaskState"] == "Completed":
  156. print("\n- Job ID = "+data[u"Id"])
  157. print("- Name = "+data[u"Name"])
  158. try:
  159. print("- Message = "+message_string[0][u"Message"])
  160. except:
  161. print("- Message = "+data[u"Messages"][0][u"Message"])
  162. print("- JobStatus = "+data[u"TaskState"])
  163. print("\n- %s completed in: %s" % (job_id, str(current_time)[0:7]))
  164. break
  165. elif data[u"TaskState"] == "Completed with Errors" or data[u"TaskState"] == "Failed":
  166. print("\n- Job ID = "+data[u"Id"])
  167. print("- Name = "+data[u"Name"])
  168. try:
  169. print("- Message = "+message_string[0][u"Message"])
  170. except:
  171. print("- "+data[u"Messages"][0][u"Message"])
  172. print("- JobStatus = "+data[u"TaskState"])
  173. print("\n- %s completed in: %s" % (job_id, str(current_time)[0:7]))
  174. sys.exit()
  175. else:
  176. print("- Job not marked completed, current status is: %s" % data[u"TaskState"])
  177. print("- Message: %s\n" % message_string[0][u"Message"])
  178. print("- Current job execution time is: %s\n" % str(current_time)[0:7])
  179. time.sleep(1)
  180. continue
  181.  
  182. def check_job_status():
  183. # Loop get commnad to check the job status of completed, completed with errors or failed
  184. #start_time=datetime.now()
  185. while True:
  186. req = requests.get('https://%s/redfish/v1/TaskService/Tasks/%s' % (idrac_ip, job_id), auth=(idrac_username, idrac_password), verify=False,cert=cert)
  187. statusCode = req.status_code
  188. data = req.json()
  189. message_string=data[u"Messages"]
  190. current_time=(datetime.now()-start_time)
  191. if statusCode == 202 or statusCode == 200:
  192. print("\n- Query job ID command passed\n")
  193. time.sleep(10)
  194. else:
  195. print("Query job ID command failed, error code is: %s" % statusCode)
  196. sys.exit()
  197. if "failed" in data[u"Messages"] or "completed with errors" in data[u"Messages"]:
  198. print("- FAIL: Job failed, current message is: %s" % data[u"Messages"])
  199. sys.exit()
  200. elif data[u"TaskState"] == "Pending":
  201. print("\n- Job ID = "+data[u"Id"])
  202. print("- Name = "+data[u"Name"])
  203. try:
  204. print("- Message = "+message_string[0][u"Message"])
  205. except:
  206. print("- Message = "+data[u"Messages"][0][u"Message"])
  207. print("- JobStatus = "+data[u"TaskState"])
  208. print("\n- %s scheduled in: %s" % (job_id, str(current_time)[0:7]))
  209. print("\n- WARNING, Host manual reboot is now needed to complete the process of applying the firmware image.\n")
  210. break
  211. elif data[u"TaskState"] == "Completed":
  212. print("\n- WARNING, device selected is immediate update, incorrect install option passed in.")
  213. print("- %s still marked completed and firmware updated" % (job_id))
  214. break
  215. elif data[u"TaskState"] == "Completed with Errors" or data[u"TaskState"] == "Failed":
  216. print("\n- Job ID = "+data[u"Id"])
  217. print("- Name = "+data[u"Name"])
  218. try:
  219. print("- Message = "+message_string[0][u"Message"])
  220. except:
  221. print("- "+data[u"Messages"][0][u"Message"])
  222. print("- JobStatus = "+data[u"TaskState"])
  223. print("\n- %s completed in: %s" % (job_id, str(current_time)[0:7]))
  224. sys.exit()
  225. else:
  226. print("- Job not marked completed, current status is: %s" % data[u"TaskState"])
  227. print("- Message: %s\n" % message_string[0][u"Message"])
  228. print("- Current job execution time is: %s\n" % str(current_time)[0:7])
  229. time.sleep(1)
  230. continue
  231.  
  232.  
  233. # Run code here
  234.  
  235. download_image_payload()
  236. install_image_payload()
  237. if install_option == "NowAndReboot" or install_option == "Now":
  238. check_job_status_host_reboot()
  239. check_new_FW_version()
  240. else:
  241. check_job_status()
  242.  
  243.  
  244. root@debian:~#
Add Comment
Please, Sign In to add comment