• No results found

Python Example of Uploading and Running a Script on a Guest Operating System

Before you perform operations on the guest operating system, you must prepare the

environment. You must create the Process.CreateSpec for initiating processes in the guest and create the Transfer.CreateSpec for the file transfer to or from the guest. The content of the optional FileAttributeCreateSpec associated with the Transfer.CreateSpec establishes the

direction of the transfer and controls guest operating system specific file attributes. You must set up equivalent _download and _upload functions for URL management of the file transfer to or from the guest. You can also create an argument parser for standard inputs, such as server, user name, and password, and you can add custom input arguments.

Procedure

1 Find the virtual machine on which the guest operating system runs, verify that VMware Tools is running, and provide credentials.

2 Create a temporary directory from which to run the script and capture any output.

3 Create temporary files for stdout and stderr. 4 (Optional) Copy the script that you want to run.

5 Start the script and capture stdout and stderr in the temporary files that you created earlier.

6 Create a loop to handle processes that run longer.

7 Create a download URL and copy the results.

8 Clean up the temporary files and directories on the guest operating system.

Python Example of Uploading and Running a Script on a Guest Operating System

This example is based on the code in the guest_ops.py sample file.

Note For a complete and up-to-date version of the sample code, see the vsphere-automation-sdk-python VMware repository at GitHub.

...

# Create the Process.CreateSpec for initiating processes in the guest def _process_create_spec(self, path, args=None, dir=None, env={}):

return Processes.CreateSpec(path=path, arguments=args, working_directory=dir, environment_variables=env)

# Create the Transfer.CreateSpec for the file transfer to/from the guest def _create_transfer_spec(self,

path,

attributes=None):

return Transfers.CreateSpec(attributes=attributes, path=path)

# Create a FileAttributeCreateSpec for a generic (non-OS specific) guest def _fileAttributeCreateSpec_Plain(self,

size,

overwrite=None, last_modified=None, last_accessed=None):

return Transfers.FileCreationAttributes(size,

overwrite=overwrite,

last_modified=last_modified, last_accessed=last_accessed)

# Create a FileAttributeCreateSpec for a linux (Posix) guest def _fileAttributeCreateSpec_Linux(self,

size,

posix = Transfers.PosixFileAttributesCreateSpec(owner_id=owner_id, group_id=group_id, permissions=permissions) return Transfers.FileCreationAttributes(size,

overwrite=overwrite,

conn = httpclient.HTTPSConnection(urloptions.netloc,

context=ssl._create_unverified_context())

conn.request("GET", urloptions.path + "?" + urloptions.query) res = conn.getresponse()

conn = httpclient.HTTPSConnection(urloptions.netloc,

context=ssl._create_unverified_context())

headers = {"Content-Length": len(body)}

# Skip server cert verification.

# This is not recommended in production code.

conn.request("PUT", urloptions.path + "?" + urloptions.query, body,

# server, username, password, cleanup and skipverification parser = sample_cli.build_arg_parser()

# Add your custom input arguments parser.add_argument('--vm_name', action='store',

help='Name of the testing vm') parser.add_argument('--root_user',

action='store',

help='Administrator account user name') parser.add_argument('--root_passwd',

action='store',

help='Administrator account password')

args = sample_util.process_cli_args(parser.parse_args()) self.vm_name = args.vm_name

session = get_unverified_session() if args.skipverification else None

# Connect to vSphere client

self.client = create_vsphere_client(server=args.server, username=args.username, password=args.password, session=session)

def run(self):

# Using vAPI to find VM.

filter_spec = VM.FilterSpec(names=set([self.vm_name])) vms = self.client.vcenter.VM.list(filter_spec)

if len(vms) != 1:

raise Exception('Could not locate the required VM with name ' + self.vm_name + '. Please create the vm first.') if vms[0].power_state != 'POWERED_ON':

raise Exception('VM is not powered on: ' + vms[0].power_state)

vm_id = vms[0].vm

# Check that vmtools svc (non-interactive user) is running.

info = self.client.vcenter.vm.guest.Operations.get(vm_id) if info.guest_operations_ready is not True:

raise Exception('VMware Tools/open-vm-tools is not running as required.')

# Establish the user credentials that will be needed for all Guest Ops APIs.

creds = Credentials(interactive_session=False, user_name=self.root_user, password=self.root_passwd,

type=Credentials.Type.USERNAME_PASSWORD)

# Step 2 - Create a temporary directory from which to run the command and capture any output tempDir = self.client.vcenter.vm.guest.filesystem.Directories.create_temporary(

vm_id, creds, '', '', parent_path=None)

# Step 3 - Create temproary files to reveive stdout and stderr as needed.

stdout = self.client.vcenter.vm.guest.filesystem.Files.create_temporary(

vm_id, creds, '', '.stdout', parent_path=tempDir)

stderr = self.client.vcenter.vm.guest.filesystem.Files.create_temporary(

vm_id, creds, '', '.stderr', parent_path=tempDir)

# Step 4 - (Optional) Copy the script to be run.

scriptPath = self.client.vcenter.vm.guest.filesystem.Files.create_temporary(

vm_id, creds, '', '.sh', tempDir)

attr = self._fileAttributeCreateSpec_Linux(size=len(script), overwrite=True, permissions='0755') spec = self._create_transfer_spec(path=scriptPath,

attributes=attr)

toURL = self.client.vcenter.vm.guest.filesystem.Transfers.create(vm_id, creds, spec) res = self._upload(toURL, script)

# Check that the uploaded file size is correct.

info = self.client.vcenter.vm.guest.filesystem.Files.get(vm_id, creds, scriptPath) if info.size != len(script):

raise Exception('Uploaded file size not as epected.')

# Step 5 - Start the program on the guest, capturing stdout and stderr in the separate temp files obtained earlier.

options = (" > " + stdout + " 2> " + stderr)

spec = self._process_create_spec(scriptPath, args=options, dir=tempDir)

pid = self.client.vcenter.vm.guest.Processes.create(vm_id, creds, spec) print('process created with pid: %s\n' % pid)

spec = self._create_transfer_spec(path=stdout) # Create the download URL

fromURL = self.client.vcenter.vm.guest.filesystem.Transfers.create(vm_id, creds, spec) body = self._download(fromURL, expectedLen=info.size)

print("--- stdout ---")

self.client.vcenter.vm.guest.filesystem.Directories.delete(vm_id, creds, tempDir, recursive=True) ...

9

The Content Library service provides means for managing content libraries in the context of a single or multiple vCenter Server instances deployed in your virtual environment. You can use the vSphere Automation APIs to access the service and use the provided functionality.

Administrators can use content libraries to share VM and vApp templates, and other types of files, such as ISO images, text files, and so on, across the vCenter Server instances in their virtual environment. Sharing templates across your virtual environment promotes consistency,

compliance, efficiency, and automation in deploying workloads at scale.

n Content Library Overview

A content library instance represents a container for a set of library items. A content library item instance represents the logical object stored in the content library, which might be one or more usable files.

n Querying Content Libraries

You can create queries to find libraries that match your criteria. You can also retrieve a list of all libraries or only the libraries of a specific type.

n Content Libraries

The Content Library API provides services that allow you to create and manage content libraries programmatically. You can create a local library and publish it for the entire virtual environment. You can also subscribe to use the contents of a local library and enable automatic synchronization to ensure that you have the latest content.

n Library Items

A library item groups multiple files within one logical unit. You can perform various tasks with the items in a content library.

n Content Library Support for OVF and OVA Packages

You can use the objects and methods provided by the Content Library API to manage OVF and OVA packages.

n Creating Virtual Machines and vApps from Templates in a Content Library

You can create VM and OVF templates from virtual machines and vApps in your inventory.

You can then deploy virtual machines and vApps from the templates that are stored in a