Last active
August 29, 2015 14:03
-
-
Save michaelrice/d3142eece43d60f9cb79 to your computer and use it in GitHub Desktop.
Revisions
-
Michael Rice revised this gist
Jul 10, 2014 . 1 changed file with 39 additions and 28 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -4,6 +4,7 @@ from __future__ import with_statement import atexit import urllib2 from pprint import pprint import requests @@ -63,6 +64,7 @@ def main(): [vim.Datacenter], True) host_system = "" # Find the datastore and datacenter we are using for dc in datacenters_object_view.view: datastores_object_view = content.viewManager.CreateContainerView( @@ -73,54 +75,63 @@ def main(): if ds.info.name == args.datastore: datacenter = dc datastore = ds host_system = datastore.host[0].key.name #print(host_system) if not datacenter or not datastore or not host_system: print("Could not find the datastore specified, or there were no " "hosts connected to it.") raise SystemExit(-1) # Clean up the views now that we have what we need datastores_object_view.Destroy() datacenters_object_view.Destroy() # Build the url to put the file to - # https://hostname:port/resource?params if not args.remote_file.startswith("/"): remote_file = "/" + args.remote_file else: remote_file = args.remote_file params = {"dsName": datastore.info.name, "dcPath": datacenter.name} http_url = "https://{0}/folder{1}?dcPath={2}&dsName={3}".format( host_system, remote_file, "ha-datacenter", datastore.name) #print("HTTP URL LOCATION") #print(http_url) # Get the cookie built from the current session #headers = { # 'Content-Type': 'application/octet-stream', # 'Cookie': cookie #} #print(headers) session_manager = content.sessionManager #pprint(session_manager) service_request_spec = vim.SessionManager.HttpServiceRequestSpec( method='httpPut', url=http_url ) pprint(service_request_spec) # Fails trying to create this ticket ticket = session_manager.AcquireGenericServiceTicket(service_request_spec) print(ticket) # Get the file to upload ready, extra protection by using with # against leaving open threads #with open(args.local_file, "rb") as f: # Connect and upload the file # request = requests.put( # http_url, params=params, # data=f, headers=headers, # verify=args.disable_ssl_verification # ) # pprint(request.status_code) except vmodl.MethodFault as e: print("Caught vmodl fault : {0}".format(e)) raise SystemExit(-1) return 0 if __name__ == "__main__": main() -
Michael Rice revised this gist
Jul 10, 2014 . 1 changed file with 41 additions and 40 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -1,10 +1,12 @@ #!/usr/bin/env python from __future__ import print_function from __future__ import with_statement import atexit from pprint import pprint import requests from pyVim import connect from pyVmomi import vmodl @@ -13,7 +15,6 @@ from tools import cli def get_args(): parser = cli.build_arg_parser() parser.add_argument('-d', '--datastore', @@ -35,48 +36,46 @@ def get_args(): args = parser.parse_args() return cli.prompt_for_password(args) def main(): args = get_args() try: service_instance = None try: service_instance = connect.SmartConnect(host=args.host, user=args.user, pwd=args.password, port=int(args.port)) except IOError: pass if not service_instance: print("Could not connect to the specified host using specified" " username and password") # Ensure that we cleanly disconnect in case our code dies atexit.register(connect.Disconnect, service_instance) content = service_instance.RetrieveContent() # Get the list of all datacenters we have available to us datacenters_object_view = content.viewManager.CreateContainerView( content.rootFolder, [vim.Datacenter], True) # Find the datastore and datacenter we are using for dc in datacenters_object_view.view: datastores_object_view = content.viewManager.CreateContainerView( dc, [vim.Datastore], True) for ds in datastores_object_view.view: if ds.info.name == args.datastore: datacenter = dc datastore = ds if not datacenter or not datastore: print("Could not find the datastore specified") raise SystemExit(-1) # Clean up the views now that we have what we need datastores_object_view.Destroy() datacenters_object_view.Destroy() @@ -87,35 +86,37 @@ def main(): else: remote_file = args.remote_file resource = "/folder" + remote_file params = {"dsName": datastore.info.name, "dcPath": datacenter.name} http_url = "https://" + args.host + ":443" + resource print("HTTP URL LOCATION") pprint(http_url) # Get the cookie built from the current session cookie = service_instance._stub.cookie cookie = cookie.split("=", 1) cookie = '$Version="1"; {0}'.format(cookie[1]) pprint(cookie) # Get the request headers set up headers = { 'Content-Type': 'application/octet-stream', 'Cookie': cookie } # Get the file to upload ready, extra protection by using with # against leaving open threads with open(args.local_file, "rb") as f: # Connect and upload the file request = requests.put( http_url, params=params, data=f, headers=headers, verify=args.disable_ssl_verification ) pprint(request.status_code) except vmodl.MethodFault as e: print("Caught vmodl fault : {0}".format(e.msg)) raise SystemExit(-1) return 0 @@ -127,7 +128,7 @@ def main(): #def download(remote_file_path, local_file_path): # resource = "/folder/%s" % remote_file_path.lstrip("/") # url = self._get_url(resource) # # if sys.version_info >= (2, 6): # resp = self._do_request(url) # CHUNK = 16 * 1024 -
Michael Rice revised this gist
Jul 10, 2014 . 1 changed file with 2 additions and 0 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,2 @@ .idea *.iml -
jaustinpage revised this gist
Jul 9, 2014 . 1 changed file with 19 additions and 12 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -1,9 +1,9 @@ #!/usr/bin/env python import requests from requests.auth import HTTPBasicAuth import atexit from pprint import pprint # used for debugging, not needed in production from pyVim import connect @@ -90,25 +90,26 @@ def main(): params = {"dsName": datastore.info.name, "dcPath": datacenter.name} http_url = "https://" + args.host + ":443" + resource print "HTTP URL LOCATION" pprint(http_url) # Get the cookie built from the current session cookie = service_instance._stub.cookie cookie = cookie.split("=", 1) cookie = "$Version=\"1\"; " + cookie[1] pprint(cookie) # Get the request headers set up headers = {'Content-Type': 'application/octet-stream', 'Cookie': cookie} # Get the file to upload ready, extra protection by using with against leaving open threads with open(args.local_file, "rb") as f: # Connect and upload the file request = requests.put(http_url, params=params, data=f, headers=headers, verify=args.disable_ssl_verification) pprint(request.status_code) except vmodl.MethodFault, e: pass @@ -139,3 +140,9 @@ def main(): # else: # urllib.urlretrieve(url, local_file_path) # # This may or may not be useful to the person who tries to use a service request in the future # Get the service request set up # service_request_spec = vim.SessionManager.HttpServiceRequestSpec(method='httpPut', url=http_url) # ticket = session_manager.AcquireGenericServiceTicket(service_request_spec) -
jaustinpage revised this gist
Jul 9, 2014 . 1 changed file with 20 additions and 27 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -1,11 +1,9 @@ #!/usr/bin/env python import requests import atexit #import mmap from pprint import pprint # used for debugging, not needed in production from pyVim import connect @@ -30,6 +28,10 @@ def get_args(): required=True, action='store', help='Path on datastore to place file') parser.add_argument('-S', '--disable_ssl_verification', required=False, action='store_true', help='Disable ssl host certificate verification') args = parser.parse_args() return cli.prompt_for_password(args) @@ -57,7 +59,6 @@ def main(): content = service_instance.RetrieveContent() session_manager = content.sessionManager # Get the list of all datacenters we have available to us datacenters_object_view = content.viewManager.CreateContainerView(content.rootFolder, @@ -88,34 +89,26 @@ def main(): resource = "/folder" + remote_file params = {"dsName": datastore.info.name, "dcPath": datacenter.name} http_url = "https://" + args.host + ":443" + resource # http_url_with_params = "https://" + args.host+ ":443" + resource + "?" + params print "HTTP URL LOCATION" # pprint(http_url) # pprint(http_url_with_parameters) # Get the service request set up # service_request_spec = vim.SessionManager.HttpServiceRequestSpec(method='httpPut', url=http_url) # ticket = session_manager.AcquireGenericServiceTicket(service_request_spec) # Get the request headers set up headers = {'Content-Type': 'application/octet-stream'} #, # 'Cookie': 'vmware_cgi_ticket=' + ticket.id } # Get the file to upload ready, extra protection by using with against leaving open threads with open(args.local_file, "rb") as f: # Connect and upload the file request = requests.put(http_url, params=params, data=f, headers=headers, auth=(args.user, args.password), verify=args.disable_ssl_verification) pprint(request.code) except vmodl.MethodFault, e: pass -
jaustinpage revised this gist
Jul 9, 2014 . 1 changed file with 66 additions and 71 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -1,11 +1,12 @@ #!/usr/bin/env python # TODO: replace urllib and urllib2 with requests import urllib, urllib2 import requests import atexit import mmap from pprint import pprint # used for debugging, not needed in production from pyVim import connect from pyVmomi import vmodl @@ -14,33 +15,13 @@ from tools import cli def get_args(): parser = cli.build_arg_parser() parser.add_argument('-d', '--datastore', required=True, action='store', help='Datastore name') parser.add_argument('-l', '--local_file', required=True, action='store', @@ -70,76 +51,71 @@ def main(): print("Could not connect to the specified host using specified " "username and password") return -1 # Ensure that we cleanly disconnect in case our code dies atexit.register(connect.Disconnect, service_instance) content = service_instance.RetrieveContent() session_manager = content.sessionManager # service_content = service_instance.RetrieveServiceContent() # Get the list of all datacenters we have available to us datacenters_object_view = content.viewManager.CreateContainerView(content.rootFolder, [vim.Datacenter], True) # Find the datastore and datacenter we are using for dc in datacenters_object_view.view: datastores_object_view = content.viewManager.CreateContainerView(dc, [vim.Datastore], True) for ds in datastores_object_view.view: if ds.info.name == args.datastore: datacenter = dc datastore = ds if not datacenter or not datastore: print ("Could not find the datastore specified") return -1 # Clean up the views now that we have what we need datastores_object_view.Destroy() datacenters_object_view.Destroy() # Build the url to put the file to - https://hostname:port/resource?params if not args.remote_file.startswith("/"): remote_file = "/" + args.remote_file else: remote_file = args.remote_file resource = "/folder" + remote_file params = {"dsName": datastore.info.name, "dcPath": datacenter.name} params = urllib.urlencode(params) http_url = "https://" + args.host+ ":443" + resource + "?" + params print "HTTP URL LOCATION" # For debugging pprint(http_url) # For debugging # Get the service request set up service_request_spec = vim.SessionManager.HttpServiceRequestSpec(method='httpPut', url=http_url) ticket = session_manager.AcquireGenericServiceTicket(service_request_spec) # Get the request headers set up headers = {'Content-Type': 'application/octet-stream', 'Cookie': 'vmware_cgi_ticket=' + ticket.id } # # Get the file to upload ready, extra protection by using with against leaving open threads # with open(args.local_file, "rb") as fd: # # Using mmap so we can handle large files # with mmap.mmpap(fd.fileno(), 0, access=mmap.ACCESS_READ) as data: # # Connect and upload the file # request = urllib2.Request(http_url, data=data, headers=headers) # if data: # request.get_method = lambda: 'PUT' # response = opener.open(request) # fd.close() # data.close() # # pprint(response) # pprint(response.code) except vmodl.MethodFault, e: pass @@ -151,3 +127,22 @@ def main(): if __name__== "__main__": main() # This may or may not be useful to the person who writes the download example #def download(remote_file_path, local_file_path): # resource = "/folder/%s" % remote_file_path.lstrip("/") # url = self._get_url(resource) # # if sys.version_info >= (2, 6): # resp = self._do_request(url) # CHUNK = 16 * 1024 # fd = open(local_file_path, "wb") # while True: # chunk = resp.read(CHUNK) # if not chunk: break # fd.write(chunk) # fd.close() # else: # urllib.urlretrieve(url, local_file_path) # -
jaustinpage created this gist
Jul 8, 2014 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,153 @@ #!/usr/bin/env python import urllib, urllib2 import requests import sys import atexit import mmap from pprint import pprint from pyVim import connect from pyVmomi import vmodl from pyVmomi import vim from tools import cli #def download(remote_file_path, local_file_path): # resource = "/folder/%s" % remote_file_path.lstrip("/") # url = self._get_url(resource) # # if sys.version_info >= (2, 6): # resp = self._do_request(url) # CHUNK = 16 * 1024 # fd = open(local_file_path, "wb") # while True: # chunk = resp.read(CHUNK) # if not chunk: break # fd.write(chunk) # fd.close() # else: # urllib.urlretrieve(url, local_file_path) # def get_args(): parser = cli.build_arg_parser() parser.add_argument('-d', '--datastore', required=True, action='store', help='Datastore name') parser.add_argument('-c', '--datacenter', required=False, action='store', help='Datacenter') parser.add_argument('-l', '--local_file', required=True, action='store', help='Local disk path to file') parser.add_argument('-r', '--remote_file', required=True, action='store', help='Path on datastore to place file') args = parser.parse_args() return cli.prompt_for_password(args) def main(): args = get_args() try: service_instance = None try: service_instance = connect.SmartConnect(host=args.host, user=args.user, pwd=args.password, port=int(args.port)) except IOError, e: pass if not service_instance: print("Could not connect to the specified host using specified " "username and password") return -1 atexit.register(connect.Disconnect, service_instance) content = service_instance.RetrieveContent() session_manager = content.sessionManager # Get the list of datastores we have available to us object_view = content.viewManager.CreateContainerView(content.rootFolder, [vim.Datastore], True) # Filter this list to a datastore that matches our name datastore = None for obj in object_view.view: if obj.info.name == args.datastore: datastore = obj # Find the hosts that are attached to this datastore all_esxi_hosts = datastore.host # Filter this list to hosts that have this datastore mounted and accessable usable_esxi_hosts = [] for esxi_host in all_esxi_hosts: if esxi_host.mountInfo.accessible and esxi_host.mountInfo.mounted: usable_esxi_hosts.append(esxi_host) chosen_esxi_host = usable_esxi_hosts[0] if not chosen_esxi_host: print "Could not find an esxi host to connect to" return -1 # Get the name of the esxi host we are going to use esxi_hostname = chosen_esxi_host.key.name # Build the url to put the file to - https://hostname:port/resource?params if not args.remote_file.startswith("/"): remote_file = "/" + args.remote_file else: remote_file = args.remote_file resource = "/folder" + remote_file params = {"dsName": datastore.info.name, "dcPath": args.datacenter} params = urllib.urlencode(params) http_url = "https://" + esxi_hostname location = resource + "?" + params http_url_location = http_url + location print "HTTP URL LOCATION" pprint(http_url_location) # Get the service request set up service_request_spec = vim.SessionManager.HttpServiceRequestSpec(method='httpPut', url=http_url_location) ticket = session_manager.AcquireGenericServiceTicket(service_request_spec) # Get the request headers set up headers = {'Content-Type': 'application/octet-stream', 'Cookie': 'vmware_cgi_ticket=' + ticket.id } # Get the file to upload ready, extra protection by using with with open(args.local_file, "rb") as fd: # Using mmap so we can handle large files data = mmap.mmap(fd.fileno(), 0, access=mmap.ACCESS_READ) # Connect and upload the file request = urllib2.Request(http_url_location, data=data, headers=headers) if data: request.get_method = lambda: 'PUT' response = opener.open(request) fd.close() data.close() pprint(response) pprint(response.code) object_view.Destroy() except vmodl.MethodFault, e: pass print "Caught vmodl fault : " + e.msg return -1 return 0 if __name__== "__main__": main()