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.
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.
- 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)
Invoke-VMScript -VM <VM> -ScriptText <COMMAND> -GuestUser <USER> -GuestPassword <PASSWORD>
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!
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!
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!
Very interesting post... but what do you do if you don't know the root password? is there a way to force upload the commands without the $gc ?