Run, Kill, and List Programs in Guest Operating System on VMware

In my last article, I announced the Guest Operating System Management API for vSphere. As promised, I will write samples to show how to use the APIs. This post explains the GuestProgramDirector type with an example.

Let’s take a quick look at the following sample:

/*=============================================================================
Copyright (c) 2012 Steve Jin, All Rights Reserved.

http://www.doublecloud.org

=============================================================================*/

package org.doublecloud.vi.vmware.guest.samples;

import java.net.URL;
import java.util.Calendar;

import org.doublecloud.vi.vmware.guest.GuestProcessDirector;

import com.vmware.vim25.GuestProcessInfo;
import com.vmware.vim25.mo.Folder;
import com.vmware.vim25.mo.InventoryNavigator;
import com.vmware.vim25.mo.ManagedEntity;
import com.vmware.vim25.mo.ServiceInstance;
import com.vmware.vim25.mo.VirtualMachine;

public class NewGuestRunProgram
{
  public static void main(String[] args) throws Exception
  {
    ServiceInstance si = new ServiceInstance(new URL("https://8.8.8.8/sdk"), "Administrator", "doublecloud.org", true);
    Folder rootFolder = si.getRootFolder();

    ManagedEntity[] mes = new InventoryNavigator(rootFolder).searchManagedEntities("VirtualMachine");
    if (mes == null || mes.length == 0)
    {
      return;
    }

    VirtualMachine vm = (VirtualMachine) mes[0];

    System.out.println("guest tool status:" + vm.getGuest().toolsRunningStatus);
    if (!"guestToolsRunning".equals(vm.getGuest().toolsRunningStatus))
    {
      System.out.println("The VMware Tools is not running in the Guest OS on VM: " + vm.getName());
      System.out.println("Exiting...");
      return;
    }

    GuestProcessDirector progDir = new GuestProcessDirector(vm, "Administrator", "vijava");

    long pid = progDir.run("C:\\Windows\\notepad.exe");
    System.out.println("pid: " + pid);

    progDir.killProcess(pid);

    GuestProcessInfo[] procInfos = progDir.listProcesses();
    for (GuestProcessInfo info : procInfos)
    {
      System.out.println("===================================");
      System.out.println("cmdLine:" + info.cmdLine);
      System.out.println("startTime:" + info.startTime.getTime());
      Calendar endTime = info.endTime;
      if (endTime != null)
        System.out.println("endTime:" + endTime.getTime());

      System.out.println("name:" + info.name);
      System.out.println("owner:" + info.owner);
      System.out.println("pid:" + info.pid);
    }
    si.getServerConnection().logout();
  }
}

To run this program, you will need to first download the new Guest Operating System Management API here , then change the related vCenter server URL/credential and guest operating system username and password. It implicitly assumes the first virtual machine is a Windows system, which is in general not a good practice but make the code easier. If it’s not true, you can either search for a Windows, or simply change the command to run.

Compared with the sample I wrote days ago (), this sample has a bit more features. Not only can it run a new program, but also kill an existing program, and list all the programs currently running in the guest operating system.

The GuestProgramDirector can actually do more the sample shows, like read the environment variables as you specify, or all of the environment variables.  There are two overloaded methods for reading environment variables as shown below: (somehow the web page just show one methd due to horizontal scroll bar. To view two, just click inside. Please let me if you know of a trick to fix this.)

public String[] readEnvironmentVariables(String[] names) throws GuestOperationsFault, InvalidState, TaskInProgress, RuntimeFault, RemoteException
public String[] readEnvironmentVariables() throws GuestOperationsFault, InvalidState, TaskInProgress, RuntimeFault, RemoteException

The first one reads only the environment variables specified with the parameter names which is an array; the second one reads all of the existing environment variables from the guest operating system. Both of them return an array of Strings. Each string in the array has format of “name=value.” The sub string before the “=” is name and after is its value.

This entry was posted in Software Development, vSphere API and tagged , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

24 Comments

  1. Atul Khandelwal
    Posted March 20, 2012 at 10:37 am | Permalink

    Hi Steve,
    This seems to be great.
    Where can I download new Guest Operating System Management API?
    Thanks
    Atul

  2. Posted March 20, 2012 at 2:59 pm | Permalink

    Hi Atul,

    Glad you like it. Here is the post with link to download it:
    http://www.doublecloud.org/2012/03/announcing-guest-operating-system-management-api-for-vsphere/

    Steve

  3. Atul Khandelwal
    Posted March 21, 2012 at 5:20 pm | Permalink

    Thanks Steve!

  4. Michael Landman
    Posted April 9, 2012 at 3:23 pm | Permalink

    Hi Steve,

    Awesome stuff! I’ve been using vijava for about a year now and love it.

    Whenever I try and use GuestProcessDirector for anything (running a command, listing processes) etc, I immediately get a com.vmware.vim25.NoPermission error. But the username and password for the VM is correct, and the same username and password work when passed as arguments to VIX’s “vmrun.exe” (for the guest system parameters). The guest OS is Windows 2k8 and has updated vmTools running on it.

    Any ideas?

  5. Posted April 12, 2012 at 12:36 am | Permalink

    Thanks Michael,
    I am glad you like vijava API. A NoPermission fault should have object and privilegeID properties. You may want to check them out on the fault you got.
    Steve

  6. kevin
    Posted May 23, 2012 at 4:38 am | Permalink

    Hi steve,
    I’m a newer for the vsphere sdk,i need to change the ip address of virtual machine which in the esxi server, can i use the GuestOperationsManager to realize it ,as i know,vsphere 5 had integrate the vix to vsphere sdk,and it had the interface of GuestOperationsManager,but i don’t know how to realize it,thanks.

  7. Posted May 23, 2012 at 10:59 pm | Permalink

    You just need to run OS specific command in the guest OS. The article has shown a sample to run notepad.exe. You can change that to guest OS commands. On Windows, for example, check out the netsh command:
    >netsh int ip set /?
    On Linux, you can try
    $ifconfig eth0 inet
    Hope it helps!
    Steve

  8. Darwin
    Posted June 6, 2012 at 9:20 am | Permalink

    Hi Steve,

    Another awesome API from you! I’m having some problems running a program in my Linux guest machine.

    This is what i have:
    GuestProcessDirector progDir = new GuestProcessDirector(vm, “root”, “password”);
    long pid = progDir.run(“touch foo”);

    I am getting an error saying: Exception in thread “main” com.vmware.vim25.FileNotFound from the progDir.run

    Am I doing this wrong?

  9. Darwin
    Posted June 6, 2012 at 9:37 am | Permalink

    Hi Steve,

    Please disregard the previous comment. I figure it had to be the full path of touch:
    progDir.run(“bin/touch”, “foo”);
    I didn’t get an error, but I can’t find the file.

  10. jayadev
    Posted July 6, 2012 at 7:06 pm | Permalink

    Hi Steve,
    I would like to change the IP address of Mgtmt interface, mask, default gateway, hostname etc of a VM while its powered OFF using PowerCLI.
    Any help?
    Thx.
    Jay

  11. Svetozar
    Posted August 24, 2012 at 6:35 am | Permalink

    Hi Steve,

    Thank you very much for contribution of this! I am new to VI Java API but I already like it because it’s simple and easy to use.
    I ‘ve just written function copyFileFromHostToGuest, but it didn’t work, so I found this post while I was searching for an idea where may be my problem. I’m happy that you’ve already created this functionality… but I am curious what is my problem.

    Do you plan to share the src of the vmguest.jar ?

    Thanks a lot,
    Svetozar Peev

  12. smcg
    Posted August 24, 2012 at 12:46 pm | Permalink

    @Svetozar
    You are probably better off posting on http://sourceforge.net/projects/vijava/forums/forum/826592 as that will make it easier to debug the problem.

  13. Homer
    Posted September 28, 2012 at 2:02 pm | Permalink

    I am trying to run this on Internal Linux commands (like “echo ABCS”) and it fails. any suggestion for those (that we don’t have an actual Path)?

    Thanks,

    Homer

  14. jack
    Posted January 28, 2013 at 5:13 am | Permalink

    Hi steve,

    How to run commends with args on linux ?eg :
    progDir.run(“/usr/bin/gnome-terminal”,”ifconfig eth0 192.168.0.198 netmask 255.255.255.0″), its nothing to chang.

    thanks a lot.

    jack

  15. Posted January 28, 2013 at 11:26 am | Permalink

    I think you can pass in the bash command path.
    Steve

  16. jack
    Posted January 28, 2013 at 9:07 pm | Permalink

    i m sorry! in centos guest machine like this: progDir.run(“/sbin/ifconfig”,”eth0 192.168.0.198 netmask 255.255.255.0″) ,It`s changed.
    thinks !

    jack

  17. jack
    Posted March 14, 2013 at 12:01 pm | Permalink

    HI Steve:
    thank you very much , Now i call this api it thorws GuestPermissionDenied exception, I had add vnic to vmware from vcenter.someone had the same exception and he said this`s bug in ESXi 5.1 , It`s true? Thanks again!

    atoka: http://communities.vmware.com/message/2191001#2191001

  18. Posted March 14, 2013 at 9:47 pm | Permalink

    Thanks Jack,
    I think what you did with VNIC seems to fit the case of the bug. It’s mentioned that 5.0u2 had fixed it. So you may want to give it a try, to be sure.
    Steve

  19. Kaustubh Khatri
    Posted July 19, 2013 at 1:04 pm | Permalink

    Hello

    Thankyou for the API. I tried it on ubuntu it works fine but for me it gives exception on windows 7. Even when I use the core vm api which is ‘ initiateFileTransferFromGuest ‘ I face the same issue. Can share if you have any thoughts on this!!

    com.vmware.vim25.SystemError
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at java.lang.Class.newInstance(Unknown Source)
    at com.vmware.vim25.ws.XmlGen.fromXml(XmlGen.java:201)
    at com.vmware.vim25.ws.XmlGen.parseSoapFault(XmlGen.java:80)
    at com.vmware.vim25.ws.WSClient.invoke(WSClient.java:133)
    at com.vmware.vim25.ws.VimStub.initiateFileTransferFromGuest(VimStub.java:4187)
    at com.vmware.vim25.mo.GuestFileManager.initiateFileTransferFromGuest(GuestFileManager.java:94)
    at org.doublecloud.vi.vmware.guest.GuestFileDirector.downloadToStream(GuestFileDirector.java:137)
    at org.doublecloud.vi.vmware.guest.GuestFileDirector.downloadFile(GuestFileDirector.java:130)
    at GetFile.getGuestFile(GetFile.java:53)
    at GetFile.main(GetFile.java:102)

  20. Mark Norman
    Posted August 22, 2013 at 9:55 am | Permalink

    I am using GuestProcessDirector successfully with Windows, but all my Ubuntu VMs get
    com.vmware.vim25.InvalidGuestLogin when I try to execute a command.
    Credentials are correct and the Ubuntu VMs are running VMware tools
    thanks

  21. Posted August 23, 2013 at 4:51 pm | Permalink

    Hi Mark,

    Are the VMware Tools up to date? Also, does your password have special chars that could fail XML like < , >, &, “, ‘? It’s escaped by vijava API, but it’s possible that it’s not reversed at server side. So try a password without these special chars.

    Good luck!

    Steve

  22. apapap
    Posted September 30, 2013 at 6:19 am | Permalink

    @Kaustubh Khatri

    Hi Kaustubh,

    I got the same error and was able to resolve it. The “com.vmware.vim25.SystemError” occurs when the guest OS you are trying to access doesn’t have a password(atleast in my case :) ). So, i assigned a password to my VM and re-ran the code and it worked.

  23. Samy
    Posted November 16, 2013 at 6:00 am | Permalink

    Dear Steve,

    I tried to your program.. i able to get the list of processes running in the guest os,but i cannot run any program in Guest OS. It does not show any error.. but its not opening the notepad.. can u help me what will be the problem?

    Thanks,
    Samy.

  24. Prabhu
    Posted November 18, 2013 at 4:26 am | Permalink

    Hi Steve,

    I executed your program.. i am able to run exe file in guest os but i am not getting the window. example: i tried to open notepad.. process is running in task manager.. but i cannot see the notepad window in guest os..
    can you give the solution for this problem??
    I am waiting for your reply!

    Thanks,
    Prabhu.

4 Trackbacks

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

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

  • NEED HELP?


    My consulting helps clients with virtualization and cloud computing, including VMware infrastructure automation and orchestration, vSphere management APIs, and deep product integration with hypervisors. Current training offerings include vSphere APIs training, vCenter Orchestrator training, and etc. Should you, or someone you know, need these consulting services or training, please feel free to contact me: steve __AT__ doublecloud.org.

    Me: Steve Jin, VMware vExpert who authored the VMware VI and vSphere SDK by Prentice Hall, and created the de factor open source vSphere Java API while working at VMware engineering. Companies like Cisco, EMC, NetApp, HP, Dell, VMware, are among the users of the API and other tools I developed for their products, internal IT orchestration, and test automation.