Advertisement
Guest User

Untitled

a guest
Mar 23rd, 2018
230
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.08 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3. # Copyright 2016 Abdul Anshad <abdulanshad33@gmail.com>
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16.  
  17. """
  18. Written by Abdul Anshad
  19. Github: https://github.com/Abdul-Anshad-A
  20. Email: abdulanshad33@gmail.com
  21.  
  22. Credits:
  23. Thanks to "reuben.13@gmail.com" for the initial code.
  24.  
  25. Note: Example code For testing purposes only
  26. vSphere Python SDK program to perform snapshot operations.
  27. """
  28.  
  29. import atexit
  30. from time import sleep
  31. import argparse
  32. import sys
  33. import time
  34. import ssl
  35. from pyVmomi import vim, vmodl
  36. from pyVim.task import WaitForTask
  37. from pyVim import connect
  38. from pyVim.connect import Disconnect, SmartConnect, GetSi
  39.  
  40.  
  41.  
  42.  
  43. def get_args():
  44. parser = argparse.ArgumentParser(description='Arguments for creating VM from template')
  45. #operating system arg
  46. parser.add_argument('--host',
  47. required= True,
  48. action='store',
  49. help='vCenter server IP or hostname')
  50. parser.add_argument('--user',
  51. required= True,
  52. action='store',
  53. help='vCenter server username')
  54. parser.add_argument('--pwd',
  55. required= True,
  56. action='store',
  57. help='vCenter server password')
  58. parser.add_argument('--name',
  59. required= True,
  60. action='store',
  61. help='VM name')
  62. parser.add_argument('--action',
  63. required= True,
  64. action='store',
  65. help='Snapshot action create/remove/revert ')
  66. parser.add_argument('--snapshot_name',
  67. required= False,
  68. action='store',
  69. help='Snapshot name')
  70. parser.add_argument('--snapshot_id',
  71. required= False,
  72. action='store',
  73. help='Snapshot id')
  74. args = parser.parse_args()
  75.  
  76. return args
  77.  
  78.  
  79.  
  80. def get_obj(content, vimtype, name):
  81. """
  82. Get the vsphere object associated with a given text name
  83. """
  84. obj = None
  85. container = content.viewManager.CreateContainerView(
  86. content.rootFolder, vimtype, True)
  87. for c in container.view:
  88. if c.name == name:
  89. obj = c
  90. break
  91. return obj
  92.  
  93.  
  94.  
  95. def get_snapshots_by_name_recursively(snapshots, snapname):
  96. snap_obj = []
  97. for snapshot in snapshots:
  98. if snapshot.name == snapname:
  99. snap_obj.append(snapshot)
  100. else:
  101. snap_obj = snap_obj + get_snapshots_by_name_recursively(
  102. snapshot.childSnapshotList, snapname)
  103. return snap_obj
  104.  
  105. def get_snapshots_by_id_recursively(snapshots, snapid):
  106. snap_obj = []
  107. for snapshot in snapshots:
  108. if snapshot.id == snapid:
  109. snap_obj.append(snapshot)
  110. else:
  111. snap_obj = snap_obj + get_snapshots_by_id_recursively(
  112. snapshot.childSnapshotList, snapid)
  113. return snap_obj
  114.  
  115.  
  116. def get_current_snap_obj(snapshots, snapob):
  117. snap_obj = []
  118. for snapshot in snapshots:
  119. if snapshot.snapshot == snapob:
  120. snap_obj.append(snapshot)
  121. snap_obj = snap_obj + get_current_snap_obj( snapshot.childSnapshotList, snapob)
  122. return snap_obj
  123.  
  124.  
  125. def main():
  126. args =get_args()
  127.  
  128.  
  129. inputs = {'vcenter_ip': args.host,
  130. 'vcenter_password': args.pwd,
  131. 'vcenter_user': args.user,
  132. 'vm_name': args.name,
  133. # operation in 'create/remove/revert'
  134.  
  135. 'operation': args.action,
  136. 'snapshot_name': args.snapshot_name,
  137. 'snapshot_id': args.snapshot_id,
  138. 'ignore_ssl': True
  139. }
  140. si = None
  141.  
  142. #print("Trying to connect to VCENTER SERVER . . .")
  143.  
  144. context = None
  145. if inputs['ignore_ssl'] and hasattr(ssl, "_create_unverified_context"):
  146. context = ssl._create_unverified_context()
  147.  
  148. si = connect.Connect(inputs['vcenter_ip'], 443,
  149. inputs['vcenter_user'], inputs[
  150. 'vcenter_password'],
  151. sslContext=context)
  152.  
  153. atexit.register(Disconnect, si)
  154.  
  155. #print("Connected to VCENTER SERVER !")
  156.  
  157. content = si.RetrieveContent()
  158.  
  159. operation = inputs['operation']
  160. vm_name = inputs['vm_name']
  161.  
  162. vm = get_obj(content, [vim.VirtualMachine], vm_name)
  163.  
  164. if not vm:
  165. print("ERROR\nVirtual Machine %s doesn't exists" % vm_name)
  166. sys.exit()
  167.  
  168. if operation != 'create' and vm.snapshot is None:
  169. print("ERROR\nVirtual Machine %s doesn't have any snapshots" % vm.name)
  170. sys.exit()
  171.  
  172. if operation == 'create':
  173. snapshot_name = inputs['snapshot_name']
  174. description = "Automated Snapshot"
  175. dumpMemory = False
  176. quiesce = False
  177.  
  178. #print("Creating snapshot %s for virtual machine %s" % (snapshot_name, vm.name))
  179. result = wait_for_task(vm.CreateSnapshot(snapshot_name, description, dumpMemory, quiesce))
  180. if (result == "true"):
  181. print("DONE")
  182. else:
  183. print("ERROR")
  184. elif operation in ['remove', 'revert']:
  185. snapshot_id = int(inputs['snapshot_id'])
  186. snap_obj = get_snapshots_by_id_recursively(vm.snapshot.rootSnapshotList, snapshot_id)
  187. #print(snap_obj);
  188. # if len(snap_obj) is 0; then no snapshots with specified name
  189. if len(snap_obj) == 1:
  190. snap_obj = snap_obj[0].snapshot
  191. if operation == 'remove':
  192. #print("Removing snapshot %s" % snapshot_name)
  193. result = wait_for_task(snap_obj.RemoveSnapshot_Task(True))
  194. if (result == "true"):
  195. print("DONE")
  196. else:
  197. print("ERROR")
  198. else:
  199. #print("Reverting to snapshot %s" % snapshot_name)
  200. result = wait_for_task(snap_obj.RevertToSnapshot_Task())
  201. if (result == "true"):
  202. print("DONE")
  203. else:
  204. print("ERROR")
  205. else:
  206. print("MESSAGE\nNo snapshots found with the id " + str(snapshot_id) + " provided on VM " + vm_name)
  207.  
  208.  
  209. else:
  210. print("Specify operation in "
  211. "create/remove/revert")
  212.  
  213.  
  214. def wait_for_task(task):
  215. """ wait for a vCenter task to finish """
  216. task_done = False
  217. while not task_done:
  218. if task.info.state == 'success':
  219. task_done = True
  220. return "true"
  221. if task.info.state == 'error':
  222. task_done = True
  223. return "false"
  224. # Start program
  225. if __name__ == "__main__":
  226. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement