Run Scripts in Linux Guests by using VMware Tools

Running commands inside a virtual machine without accessing it can be helpful in some cases. For example when you want to change an IP address from a Linux virtual machine that is not reachable through ssh. VMware provides the VIX (Virtual Infrastructure eXtension) API that helps you to write scripts to automate virtual machine operations and run programs within guest operating systems. I am going to show some basic VIX implementations using PowerCLI.

PowerCLI (Invoke-VMScript)

The PowerShell Invoke-VMScript cmdlet is included in VMware vSphere PowerCLI package. It enables you to run commands inside guest virtual machines. All stdout (Standard output) is reditected to the PowerCLI cmdlet and can be displayed or stored in an variable.

Requirements

  • VMware Tools have to be installed and running inside the guest
  • Guest OS requires authentication
  • The cmdlet does not work with 64-Bit PowerCLI. You have to use PowerCLI 32-Bit
  • You have connect to a vCenter Server (Connect-VIServer)

Basic Usage

Invoke-VMScript -VM <VM> -ScriptText <COMMAND> -GuestUser <USER> -GuestPassword <PASSWORD>

Example
I am not going into different Linux commands, i just use ifconfig to show the current ip address configuration from my vMA:

Invoke-VMScript -VM vma.virten.local -ScriptText "ifconfig" -GuestUser root -GuestPassword VMware!

invoke-vmscript

Command as Variable
You can use a variable as Command which helps when writing PowerShell scripts to build dynamic commands:

$command = "ifconfig"
Invoke-VMScript -VM vma.virten.local -ScriptText $command -GuestUser root -GuestPassword VMware!

Secure Credentials
Using clear-text passwords in scripts is a bad idea. PowerShell provides the Get-Credential cmdlet to securely store passwords:

$gc = Get-Credential
$command = "ifconfig"
Invoke-VMScript -VM vma.virten.local -ScriptText $command -GuestCredential $gc


Error: Object reference not set to an instance of an object.
Invoke-VMScript : 13.06.2013 22:18:52    Invoke-VMScript        Object reference not set to an instance of an object.
If you get this error message check which PowerCLI Version you are running. Invoke-VMScript does only support 32-Bit PowerCLI!

Leave a Comment

NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>