Advertisement
Guest User

Untitled

a guest
Aug 3rd, 2016
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.64 KB | None | 0 0
  1. #!/usr/bin/env python
  2. """
  3. vSphere Python SDK program for shutting down VMs
  4. """
  5. from __future__ import print_function
  6.  
  7. from pyVim.connect import SmartConnect, Disconnect
  8. from pyVmomi import vim, vmodl
  9.  
  10. import argparse
  11. import atexit
  12. import getpass
  13. import sys
  14. import ssl
  15.  
  16.  
  17.  
  18. def GetArgs():
  19. """
  20. Supports the command-line arguments listed below.
  21. """
  22.  
  23. parser = argparse.ArgumentParser(description='Process args for shutting down a Virtual Machine')
  24. parser.add_argument('-s', '--host', required=True, action='store', help='Remote host to connect to')
  25. parser.add_argument('-o', '--port', type=int, default=443, action='store', help='Port to connect on')
  26. parser.add_argument('-u', '--user', required=True, action='store', help='User name to use when connecting to host')
  27. parser.add_argument('-p', '--password', required=False, action='store', help='Password to use when connecting to host')
  28. parser.add_argument('-v', '--vmname', required=True, action='append', help='Names of the Virtual Machines to shutdown')
  29. args = parser.parse_args()
  30. return args
  31.  
  32.  
  33. def main():
  34. """
  35. Simple command-line program for shutting down virtual machines on a system.
  36. """
  37.  
  38. args = GetArgs()
  39. if args.password:
  40. password = args.password
  41. else:
  42. password = getpass.getpass(prompt='Enter password for host %s and user %s: ' % (args.host,args.user))
  43.  
  44. service_instance = None
  45. context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
  46. context.verify_mode = ssl.CERT_NONE
  47.  
  48. try:
  49. service_instance = SmartConnect(host=args.host,
  50. user=args.user,
  51. pwd=args.password,
  52. port=int(args.port),
  53. sslContext=context)
  54. if not service_instance:
  55. print("Could not connect to the specified host using specified "
  56. "username and password")
  57. return -1
  58.  
  59. atexit.register(Disconnect, service_instance)
  60.  
  61. content = service_instance.RetrieveContent()
  62. # Search for all VMs
  63. objview = content.viewManager.CreateContainerView(content.rootFolder,
  64. [vim.VirtualMachine],
  65. True)
  66. vmList = objview.view
  67. objview.Destroy()
  68.  
  69. for vm in vmList:
  70. print("Shutting down VM: %s" % vm.name)
  71. vm.ShutdownGuest()
  72.  
  73. except vmodl.MethodFault as error:
  74. print("Caught vmodl fault : " + e.msg)
  75. return -1
  76.  
  77. return 0
  78.  
  79. # Start program
  80. if __name__ == "__main__":
  81. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement