Home
VMware Scripting API User`s Manual
Contents
1. Introduction 7 Introducing the VMware Scripting APIs 8 Supported Products 8 Intended Audience 9 Getting Support from VMware 9 What s New in This Release 0 Using the VMware Scripting APIs 3 Installing the VMware Scripting API 4 GSX Server 4 ESX Server 4 nstalling the VMware Scripting API on a Windows Machine 4 nstalling VmPerl Scripting API on a Linux Machine 5 Using VmCOM 17 Using Symbolic Links 8 Snapshots and Redo Logs 8 Disk Device Names 9 VmCOM Objects 9 VmConnectParams 20 VmsServerCtl 21 Property 2 Methods 2 VmcCollection 23 VmCtl 24 Properties 24 ethods 26 VmQuestion 32 Symbolic Constant Enumerations 33 VmExecutionState 33 VmPowerOpMode 33 VmpProdinfoType 34 VmProduct 35 VmPlatform 35 Using VmCOM to Pass User Defined Information Between a Running Guest Operating System and a Script 36 Guestinfo Variables 36 Sending Information Set in a VmCOM Script to the Guest Operating System _ 37 Sending Information Set in the Guest Operating System to a YmCOM Script _ 37 Using Sample VmCOM Programs 39 Copyright Information MiniMUI Visual Basic Sample Program JScript and VBScript Sample Programs JScript Sample Program 1 VBScript Sample Program 2 VBScript Sample Program 3 l JERNSES 53 Using VmPerl Using Symbolic Links 54 Snapshots and Redo Logs 55 Disk Device Names 55 VMwar
2. VmProduct Values Description vmProduct WS The product is VMware Workstation vmProduct GSX The product is VMware GSX Server vmProduct_ESX The product is VMware ESX Server vmProduct_UNKNOWN The product type is unknown VmPlatform The VmPlat form symbolic constant enumeration denotes a VMware machine s platform type The Product Info property returns this information when the requested product information type is vmProdInfo_ Platform VmPlatform Values Description vmPlatform_WINDOWS The host platform is a Microsoft Windows operating system vmPlatorm_LINUX The host platform is a Linux operating system vmPlatform_VMNIX The host platform is the ESX Server console operating system vmPlatform_UNKNOWN The host platform is unknown 35 VMware Scripting API User s Manual 36 Using VmCOM to Pass User Defined Information Between a Running Guest Operating System and a Script When the guest operating system is running inside a virtual machine you can pass information from a script running in another machine to the guest operating system and from the guest operating system back to the script through the VMware Tools service You do this by using a class of shared variables commonly referred to as Guestinfo VMware Tools must be installed and running in the guest operating system before a Guestinfo variable can be read or written inside the guest operating system For example create and connect
3. www vmware com CHAPTER 8 VMware ESX Server Resource Variables Variable Name Variable Type Description system mem cptread INT Sum of cptread KB read from suspend files for all running virtual Note This is not supported in ESX machines Server 3 system mem mctltgt INT Total amount of memory in KB that the vmmemct 1 balloon drivers Note This is not supported in ESX should reclaim from all guest operating systems in running virtual Server 3 machines The value of system mem memctl should always approach this number system mem memctl NT Total amount of memory in KB that the vmmemct 1 balloon drivers have reclaimed from all guest operating systems in running virtual machines system mem overhd NT Sum of the current overhead memory in KB for all running virtual machines system mem ovhdmax NT Sum of the maximum overhead memory in KB for all running virtual machines system mem reservedMem NT Reserved memory in KB across all running virtual machines This Note This applies only to ESX number is the total of user set minimum memory sizes and the Server 2 1 1 and higher default minimum memory sizes 50 of the specified maximum on all virtual machines system mem reservedSwap INT Reserved swap space in KB across all virtual machines This value is Note This applies only to ESX equal to the difference between the max maximum memory size Server 2 1 1 and hi
4. Instructions for Windows 2000 and later operating systems save the contents of this file to a file named samplel js unless it s already named that way there should be an accompanying file named samplel wsf It is placed in the same directory as this file during product installation This file is responsible for setting up the Windows Script Host environment and loading the VmCOM type library thereby enabling this script to reference symbolic constants such as vmExecutionState_On in a command line window type Jf cscript nologo samplel wsf cp WScript CreateObject VmCOM VmConnect Params server WScript CreateObject VmCOM VmServerCt1 server Connect cp vmCollection server RegisteredVmNames for j 1 j lt vmCollection count j vmName vmCollection j vm WScript CreateObject VmCOM VmCt1 vm Connect cp vmName str config path vmName OS vm Config guestOS state execStateString State2Str vm str execStateString if execStateString STUCK question vm PendingQuestion str pending question question text choices choices question choices for i 1 i lt choices count i str choices i WScript Echo str 43 VMware Scripting API User s Manual 44 function State2Str vm switch vm ExecutionState case vmExecutionSt
5. eSystem mem With ESX Server 3 you must now specify the CPU number to query CPU stats resource variables The Scripting API has previously allowed a user to query CPU stats without specifying a CPU number For example vmware cmd lt vm_cfg gt get_resource cpu usedsec vmware cmd lt vm_cfg gt get resource cpu waitsec When querying CPU stats while connected to ESX Server 3 the Scripting API now requires a CPU number in the name of the resource variable For example vmware cmd lt vm cfg gt get resource cpu 1 usedsec vmware cmd lt vm cfg gt get resource cpu 0 waitsec COSavail cosUsage cpt tgt cptread memctltgt reservedSwap swaptgt sysCodeSize totalSwap vmkernel CHAPTER 1 Introduction 11 VMware Scripting API User s Manual www vmware com 12 CHAPTER 1 Introduction Using the VMware Scripting APIs By using the VMware Scripting APIs you can access and administer virtual machines without using a local or remote console The virtual machines or the server for that matter do not have to be running in order to use the VMware Scripting APIs Note We support a maximum of two scripting connections to a virtual machine at a time Each VmCOM object and Perl module is described in the following chapters and includes the methods the properties and their usage In addition sample scripts and lists of error codes are provided For VmCOM sample scripts see Using Sample VmCOM Programs on page 39 and
6. my port undef my connect params VMware VmPerl ConnectParams new server_name Sport user passwd my vm VMware VmPerl VM new if vm gt connect connect params Scfg path my Serror number Serror string Svm gt get last error die Could not connect to vm Error Serror number Serror_string n Get the power status of the virtual machine my Scur_ state Svm gt get execution state if defined cur_state my Serror number Serror string Svm gt get last error die Could not get execution state Error Serror number Serror_string n print The execution state of cfg_ path is Sstate string _map gt cur_state n Destroys the virtual machine object thus disconnecting from the virtual machine undef vm www vmware com 86 CHAPTER 5 Using Sample VmPerl Scripts Monitoring a Virtual Machine s Heartbeat The following sample Perl script provides one method to monitor a virtual machine s heartbeat If the heartbeat is lost or is not detected the script powers on a second instance of the virtual machine This script nb check p1 saved with a TXT extension for online viewing can be found on the VMware Web site at www vmware com support developer scripting APl doc hbcheck p1 txt usr bin perl w Copyright C 1998 2004 VMware Inc hbcheck pl ConfigToCheck for a heartbeat within a certain interval in seconds If no heartbeat is received w
7. lt n gt where lt m gt is the virtual controller number and lt n gt is the virtual SCSI device number www vmware com Each virtual disk has a unique combination of virtual controller number and virtual device number CHAPTER 7 vmware cmd Utility that compose the disk device name If you know the name of the virtual disk file you can locate the corresponding numbers in To determine the numbers in th configuration file For each virtu contains a line identifying the vi he virtual machine s configuration file e disk device name view the contents of the virtual machine al disk belonging to the virtual machine the configuration file rtual disk file that acts as the backing store for the virtual SCSI disk You use this line to find the numbers belonging to the file name of the virtual disk For example if the configuration file contains the following line scsi0 1 name My VM then you know that the disk device name forMy_VM_disk_2is scsi0 1 representing virtual FS My VM disk 2 vmdk SCSI device 1 on virtual control Operations er 0 of that virtual machine Note The following table includes some ESX Server and GSX Server specific methods and are specifically noted Virtual Machine Operation Description vmware cmd lt vm cfg path gt getstate vmware cmd lt vm cfg path gt start lt powerop_mode gt Retrieves the execution state of a virtual machine on off suspended stuck
8. undef For Windows Guest OS if S 0 eq MSWin32 S ipconfig iparr IP Address d d d d ig Smyip iparr 0 For Linux Guest OS Please ensure that ifconfig is in your path The root user has it by default else S ifconfig iparr inet addr d d d d ig Smyip Siparr 0 return Smyip Stores the IP address in the guestinfo name space sub set_ip variable if 0 eq MSWin32 Please ensure that VMwareService is in your path VMwareService needs double quotes around the command 97 VMware Scripting API User s Manual mun i my cmd VMwareService cmd info set guestinfo ip ip system cmd else Please ensure that vmware guestd is found in the path used below system etc vmware vmware guestd cmd info set guestinfo ip ip return www vmware com 98 CHAPTER 5 Using Sample VmPerl Scripts Getting a Virtual Machine s IP Address This script runs in the host operating system or another machine and invokes the VMware Perl API to retrieve the value of the ip variable a virtual machine s IP address This sample script complements the preceding sample script Setting a Virtual Machine s IP Address Configuration Variable on page 96 that sets a virtual machine s IP address configuration variable in the guest operating system For more information on pas
9. Powers on a previously powered off virtual machine or resumes a suspended virtual machine where mode specifies the operation s behavior based on the value of the VMware VmPerl VM_POWEROP_MODE_ lt XXX gt where lt XXX gt is HARD SOFT or TRYSOFT If mode is not specified the default mode is VM_POWEROP_MODE_SOFT For more information see VM_POWEROP_MODE_ lt XXX gt Values on page 70 Note If you are connecting to GSX Server 1 x or ESX Server 1 x then you must specify VMware VmPerl VM_POWEROP_MODE_HARD as the mode or the operation will fail f the virtual machine is powered off then it is powered on If it is suspended this method resumes the virtual machine If the virtual machine is in any other state the start method fails and throws an error Svm gt stop mode Returns the defined value on success or undef undefined value on failure Shuts down and powers off a virtual machine where mode specifies the operation s behavior based on the value of the VMware VmPerl VM POWEROP MODE lt XXX gt where lt XXX gt is HARD SOFT or TRYSOFT If mode is not specified the default mode is VM POWEROP MODE SOFT For more information see VM POWEROP MODE lt XXX gt Values on page 70 Note If you are connecting to GSX Server 1 x or ESX Server 1 x then you must specify VMware VmPerl VM POWEROP MODE HARD as the mode or the operation will fail This method always fails if the virtual machine is not in the VM EXECUTION S
10. The VmCt 1 object exposes the following symbolic constant enumerations where each element of an enumeration is a symbolic constant VmeExecutionState VmPowerOpMode VmpProdinfoType VmProduct VmPlatform VmExecutionState The VmExecut ionState symbolic constant enumeration specifies the state or condition of a virtual machine The possible values are listed in the following table VmExecutionState Values Description vmExecutionState On The virtual machine is powered on vmExecutionState Off The virtual machine is powered off vmExecutionState Suspended The virtual machine is suspended vmExecutionState Stuck The virtual machine requires user input The user must answer a question or dismiss an error vmExecutionState Unknown The virtual machine is in an unknown state VmPowerOpMode The VmPowerOpMode symbolic constant enumeration specifies the behavior of a power transition start stop reset or suspend method During a soft power transition the VMware Tools service runs a script inside the guest operating system For example the default scripts that run during suspend and resume operations respectively release and renew DHCP leases for graceful integration into most corporate LANs You may also customize these scripts For more information on using these scripts see your VMware product documentation The following table includes the possible values for a VmPowerOpMode symbolic co
11. This property does not apply to ESX Server 3 integer Returns the process ID of a running virtual machine Resource lt variable_name gt Note only to This property applies ESX Server string GET PUT Accesses the value of a virtual machine resource variable identified by the string lt variable_name gt The property throws an error if it accesses an undefined variable See Virtual Machine Resource Variables for ESX Server on page 135 for a list of virtual machine variables 25 VMware Scripting API User s Manual 26 Property Name Property Type Access Type Description Id string Note This property applies only to ESX Server 2 and earlier GET Returns a unique ID for a running virtual machine Note This property applies Capabilities integer GET Returns the access permissions for the current user This number is a bit vector where 4 read 2 write Note This property applies only to ESX Server 2 and earlier fthe guest operating system only to ESX Server 2 and and 1 execute For a user with all three permissions a earlier value of 7 is returned when this property is used in a script RemoteConnections integer GET Returns the number of remotely connected users This value includes the number of remote consoles Scripting APIs and Web based management interface connections to the virtual machine Additional Informati
12. requires user input or unknown Powers on a previously powered off virtual machine or resumes a suspended virtual machine Hard soft or trysoft specifies the behavior of the power operation lt powerop_mode gt If lt powerop_mode gt is not specified the default behavior is soft For more information see lt powerop_mode gt Values on page 125 vmware cmd lt vm cfg path gt stop lt powerop_mode gt vmware cmd lt vm cfg path gt reset lt powerop_mode gt Shuts down and powers off a virtual machine Hard soft or trysoft specifies the behavior of the power operation lt powerop_mode gt If lt powerop_mode gt is not specified the default behavior is soft For more information see lt powerop_mode gt Values on page 125 Shuts down then reboots a virtual machine Hard soft or trysoft specifies the behavior of the power operation lt powerop_mode gt If lt powerop_mode gt is not specified the default behavior is soft For more information see lt powerop_mode gt Values on page 125 vmware cmd lt vm cfg path gt suspend lt powerop_mode gt Suspends a virtual machine Hard soft or trysoft specifies the behavior of the power operation lt powerop_mode gt If lt powerop_mode gt is not specified the default behavior is soft For more information see lt powerop_mode gt Values on page 125 119 VMware Scripting API User s Manual 120 Virtual Machine Operation Description
13. string GET PUT Retrieves and sets the user s password on the server 20 www vmware com CHAPTER 2 Using VmCOM VmServerCtl The VmServerCt1 object represents a VMware server running on a particular machine Property The VmServerCt1 object includes the properties listed in the following table All of the properties can be retrieved GET some of the properties can also be modified PUT Note The Resource property applies only to ESX Server Property Name Property Type Access Type Description RegisteredVmNames string GET Returns a VmCollection of strings specifying the configuration file names of the virtual machines currently registered on the server The server must be connected using Connect or this property throws an error Resource lt variable_name gt string GET PUT Accesses the value of a ESX Server system resource Note This property applies variable identified by the string only to ESX Server lt variable_name gt The property throws an error if it accesses an undefined system variable See VMware ESX Server System Resource Variables on page 130 fora list of server system variables Methods The VmServerCt1 object also exposes the methods listed in the following table Except where noted otherwise these methods are synchronous the method does not return until it finishes its operation fails or times out Most operations time out after 2 minutes Note ESX
14. unless Sop ok my Serr Serrstr Svm gt get last error undef vm die Could not answer pending question error Serr errstr n Destroys the virtual machine object thus disconnecting from the virtual machine undef vm Prints answer choices prompts user for an answer number sub prompt my choices shift print To answer the question type the number that corresponds to n print one of the answers below n for my i 0 i lt choices i print t i 1 S choices i n print Final answer Reads user s answer number sub get_answer my Sanswer chop Sanswer lt STDIN gt print n Remove unintentional whitespace Sanswer s s s 2 return Sanswer Checks if an answer number is within the valid range of choices sub valid answer my Sanswer shift my echoices shift www vmware com CHAPTER 5 Using Sample VmPerl Scripts Sanswer convert to 0 based indexing if answer lt 0 Sanswer gt choices my num scalar choices print Valid answer numbers are from 1 to num please try again n return 0 else return 1 93 VMware Scripting API User s Manual 94 Suspending a Virtual Machine A script like the following allows you to suspend a virtual machine remotely without connecting to it through a remote console or the VMware Management Interface This script suspend p1 saved wi
15. 58 60 Sdev_name 66 Sinfotype 65 71 72 Skey_name 64 74 75 mode 61 Squestion 66 vm name 60 A access permissions 26 67 124 add redo method 62 adding 28 62 120 adding redo log 28 62 120 AddRedo method 28 answer question method 66 answering a question 32 53 65 66 69 90 93 111 113 114 123 AnswerQuestion method 30 32 108 API incompatible with server 109 authd 112 c Capabilities property 26 checking for existence of snapshots 30 64 122 choice 30 Choices property 23 30 32 collection object 18 command cscript 42 48 Commit method 29 commit method 63 committing redo log changes 29 63 121 concepts VmCOM 17 VmPerl 53 Config property 24 31 config ini file 111 ConfigFileName property 25 configuration file for virtual machine 18 22 24 27 54 59 60 65 109 123 configuration variable 24 65 96 98 99 100 122 Connect method 17 20 22 27 108 109 connect method 54 58 60 109 Connect_device method 66 ConnectDevice method 31 connected users 26 67 124 connecting to a device 31 66 123 to a server 17 22 27 53 58 60 to a virtual machine 27 60 110 connection parameters 17 20 22 27 58 60 connection security 20 56 connections total number of simulta neous 22 27 58 60 Count property 23 CPU statistics 130 135 137 create_snapshot method 63 CreateSnapshot method 30 creating snapshots 30 63 122 cscript 42 48 D
16. DISCONNECT 109 SUFFICIENT_RESOURCES 58 o VALIDARGS 109 VALIDVM 109 EEDINPUT 109 ETFAIL 109 OACCESS 109 OMEM 109 OPROPERTY 109 OSUCHVM 110 OTCONNECTED 110 OTSUPPORTED 110 ROXYFAIL 110 MEOUT 110 UNSPECIFIED 110 _E_VMBUSY 110 E VMEXISTS 110 _E_VMINITFAILED 110 EXECUTION_STATE_ lt XXX gt 70 POWEROP MODE lt XXX gt 61 62 Li o PRODINFO PLATFORM lt XXX gt 72 PRODINFO PRODUCT lt XXX gt 72 VmcCollection 18 23 VmCOM AddRedo method 28 AnswerQuestion method 30 32 108 Commit method 29 concepts 17 Connect method 17 20 22 27 108 109 So NS SS e Ss oS SS ee Oe SS 146 www vmware com ConnectDevice method 31 CreateSnapshot method 30 DisconnectDevice method 31 error handling 108 HasSnapshot method 30 RegisterVm method 22 RemoveSnapshot method 30 Reset method 28 RevertToSnapshot method 30 sample scripts 15 39 51 Start method 27 Stop method 27 Suspend method 28 UnregisterVm method 22 use with Windows operating system 7 VmConnectParams 17 20 22 27 VmCtl 17 24 31 36 108 VmCtl AddRedo 28 VmCtl AnswerQuestion 30 32 108 VmCtl Commit 29 VmCtl Connect 20 27 VmCtl ConnectDevice 31 VmCtl CreateSnapshot 30 VmCtl DisconnectDevice 31 VmCtl HasSnapshot 30 VmCtl PendingQuestion 30 32 108 VmCtl RemoveSnapshot 30 VmCtl Reset 28 VmCtl RevertToSnapshot 30 VmCtl Stop 27 VmCtl S
17. This method always fails if the virtual machine is not in the VMware VmPerl VM_EXECUTION_STATE_ON state Svm gt add_redo disk Returns the defined value on success or undef undefined value on failure Note This method applies only to ESX Server 2 and earlier This method adds a redo log to a running virtual SCSI disk specified by disk that is associated with the virtual machine specified by vm Changes made to the virtual disk accumulate in the new redo log This disk must be a ESX Server virtual disk stored on a VMFS volume disk is a string containing the disk device name The format of the disk device name is explained in the section Disk Device Names on page 55 The virtual disk can be in persistent undoable or append mode The redo log for a virtual disk in persistent mode uses the file name of the virtual disk with REDO appended to it for example if the disk is called vm dsk the redo log is called vm dsk REDO A virtual disk in undoable or append mode already has a redo log associated with it so the new redo log you create is called vm dsk REDO REDO whose parent is the existing redo log vm dsk REDO This method fails if the specified virtual disk does not exist the specified virtual disk is in nonpersistent mode an online commit is already in progress or the virtual disk already has two redo logs associated with it If you add a redo log using the vm gt add redo method but do
18. device connecting to 31 66 123 device disconnecting from 31 66 123 device_is_connected method 66 DevicelsConnected property 25 devName 31 DHCP lease 33 70 disconnect_device method 66 DisconnectDevice method 31 disconnected virtual machine 110 disconnecting from a device 31 66 123 disk statistics 132 138 E error condition requiring user input 32 53 66 69 111 113 114 141 142 error handling 108 error YmCOM 109 110 vmErr BADSTATE 31 109 vmErr BADVERSION 109 vmErr DISCONNECT 108 109 vmErr INSUFFICIENT RESOURCES 109 vmErr INVALIDARGS 109 vmErr INVALIDVM 109 vmErr NEEDINPUT 108 109 vmErr NETFAIL 109 network statistics 133 set resource variable 21 59 117 ESX Server resource variable 130 134 event ID 112 Event Viewer 111 114 ExecutionState property 24 G ge ge resource variable 21 25 59 67 117 123 _ capabilities method 67 vmErr vmErr vmErr VmErr vmErr vmErr OACCESS 109 OMEM 109 OPROPERTY 109 OSUCHVM 110 OTCONNECTED 108 110 OTSUPPORTED 110 get choices method 66 69 get config method 65 get config file name method 64 get connected users method 64 vmErr PROXYFAIL 110 vmErr TIMEOUT 110 ge ge execution state method 64 guest info method 64 75 vmErr NSPECIFIED 110 vmeErr_VMBUSY 110 vmeErr_VMEXISTS 110 vmeErr_VMINITFAILED 110 error VmPerl 109 110 V S lt SSSSSSSSSSSSSSLASE
19. lt job gt VBScript Sample Program 3 This VBScript sample program lists then starts locally registered virtual machines that are not already running on a server This script powers on powered off virtual machines and resumes suspended virtual machines that have the line autostart true in their configuration files This script includes a slight delay after starting each virtual machine This delay balances the load on the server Do not start many virtual machines in rapid succession without this delay You can use a script like the following to start selected virtual machines automatically after a server boots However this script must be configured as a service for it to run without requiring a login from a user 47 VMware Scripting API User s Manual 48 Tools exist that allow any application including a script to run as a service One example is the instsrv and srvany programs from the Microsoft Windows 2000 Resource Kit If you use srvany to implement the service then configure your service to launch the cscript program Set the program s argument to the path of the script s ws file Refer to the Microsoft Windows 2000 Resource Kit documentation for more details If you choose to use a different tool then refer to your specific tool s documentation to configure the script to run as a service The source for the sample program 3 script is in the SampleScripts folder in the VmCOM Scripting API directory You can also
20. script automatically keeps the redo log during a shutdown operation or appends the redo log during a power on operation Note The script s question answering code is highly dependent on the version of your server product and the language used in the question This script can malfunction with a newer version of the server product or different language version of the VMware server product This sample program is for example purposes only and is written for VMware GSX Server The source for the sample program 2 script is in the SampleScripts folder in the YmCOM Scripting API directory You can also find it on the VMware Web site saved with a TXT extension for online viewing at www vmware com support developer scripting AP doc sample2 vbs txt VmCOM VBScript Sample Script sample2 Copyright c 1998 2004 VMware Inc This program is for educational purposes only It is not to be used in production environments Description This script displays the virtual machines on the local server It prints the configuration file path and current execution state of each VM If a VM is in the stuck state the current question and its choices are also printed Additionally if a VM is stuck on an undoable disk related question the script automatically answers Keep on a power off and Append on a power on NOTE the question answering logic used is language and product dependent and is only provided for illustr
21. virtual disk n exit 1 my serverName user Spasswd Scfg Sdisk ARGV Use the default port my Sport undef Open up a VM object for the virtual machine associated with the specified config file my Sparams VMware VmPerl ConnectParams new serverName Sport user Spasswd my Svm VMware VmPerl VM new my Serr vm gt connect params cfg if defined Serr my SerrorNumber SerrorString S vm gt get last error die Cannot connect to vm Error SerrorNumber errorString n Add a REDO log to the specified disk Serr vm gt add redo Sdisk if defined Serr my SerrorNumber SerrorString vm sget_last_error die Cannot add redo log Error errorNumber errorString n vm gt disconnect www vmware com 102 CHAPTER 5 Using Sample VmPerl Scripts Committing a Redo Log to a Virtual Disk without Freezing the Virtual Machine ESX Server 2 x only To use this script you must have a virtual disk with two redo logs lt di sk gt REDO and lt disk gt REDO REDO You can use this script to commit a virtual disk s redo log lt disk gt REDO to its virtual disk You specify the disk on the command line or let the script give you a choice to select of disks that are associated with the virtual machine The virtual machine is not frozen when the redo log lt disk gt REDO is committed to the virtual disk but the script waits until the commit finishe
22. vm gt add redo method please see VMware VmPerl VM on page 60 This script addredo p1 saved with a TXT extension for online viewing can be found on the VMware Web site at www vmware com support developer scripting API doc addredo pl txt Note This script applies only to ESX Server 1 x and 2 x usr bin perl w Copyright C 1998 2004 VMware Inc addredo pl This script takes a specification of a server name user password and the path for the config file of a virtual machine on that server It then displays the disks in the virtual machine configuration allows the user to choose a disk and then adds a redo log to that disk The user can also specify the disk directly as the fifth argument on the command line usage addredo pl server user password config virtual disk BEGIN if O0 eq MSWin32 INC 5 00503 lib 5 00503 lib MSWin32 x86 auto 5 00503 1ib MSWin32 x86 site 5 00503 1ib site 5 00503 1ib MSWin32 x86 auto 101 VMware Scripting API User s Manual site 5 00503 1lib MSWin32 x86 else push INC usr lib perl5 site perl 5 005 1386 linux usr lib per15 5 00503 We use VMware VmPerl use VMware VmPerl Server use VMware VmPerl ConnectParams use VMware VmPerl VM use strict if ARGV 4 amp amp ARGV 5 print Usage 0 server user password path to config file
23. 1 x then you must specify VMware VmPerl VM_POWEROP_MODE_HARD as the mode or the operation will fail During a soft power transition the VMware Tools service runs a script inside the guest operating system For example the default scripts that run during suspend and resume operations respectively release and renew DHCP leases for graceful integration into most corporate LANs You may also customize these scripts For more information on these scripts see your VMware product documentation Refer to the section on executing scripts The possible values are listed in the following table www vmware com CHAPTER 4 Using VmPerl Powerop_mode Values Description VM_POWEROP_MODE_SOFT To succeed soft power transitions require the current version of the Vmware Tools service to be installed and running in the guest operating system Start when a virtual machine is suspended After resuming the virtual machine the operation attempts to run a script in the guest operating system to restore network connections by renewing the DHCP lease The S not present or is malfunctioning the running of the script may fail art operation always succeeds However if the VMware Tools service is Start when virtual machine is powered off After powering on the virtual machine it attempts to run a script in the guest operating system when the VMware Tools service becomes active This default script does nothing
24. 125 U undoable disk 44 uninstalling VmPerl 16 145 unregister_vm method 59 unregistering virtual machine 117 Unregistervm method 22 uptime 25 67 123 Uptime property 25 user input 30 32 53 65 66 69 90 93 111 113 114 123 user name 20 56 116 user permissions 26 67 124 users connected 26 67 124 V variable 24 36 38 65 73 75 122 VBScript 42 44 47 47 51 virtual device 25 31 66 123 virtual machine 25 53 60 68 73 123 configuration file 18 22 24 27 54 59 60 65 109 123 connecting to 27 60 110 CPU statistics 135 137 disconnected 110 disk statistics 138 event logging 111 114 execution state 33 70 heartbeat 25 65 87 89 123 ID 26 67 123 list of 18 42 44 44 47 47 51 54 80 81 82 84 117 memory size 24 65 122 memory statistics 137 138 network failure 109 network statistics 138 139 no response 110 power operations 27 28 33 61 62 70 111 113 power state 24 64 85 86 119 process ID 25 67 124 reconnect 27 registering 58 110 117 resetting 28 33 34 61 70 71 119 125 security 20 56 set resource variable 25 67 123 starting 27 33 34 47 51 61 70 71 82 84 119 125 stopping 27 33 34 61 70 71 119 125 suspending 28 33 34 62 70 71 94 95 119 125 unregistering 117 VmCtl 17 24 31 36 108 waiting for input 30 32 66 108 virtual machine resource variable 135 139 Visual Basic 41 108 vm See virtual machine _BADSTATE 66 109 BADVERSION 109
25. 99 100 setting a configuration variable 96 98 suspending a virtual machine 94 95 sample scripts VmPerl 16 script 36 38 73 75 security 20 56 109 server connecting to 17 22 27 42 44 44 47 53 58 60 incompatible with API 109 security 20 56 virtual machines on 18 VmServerCtl 17 21 22 108 VMware VmPerl Server 53 58 59 serverd 112 set config method 65 66 set guest info method 64 74 set resource method 59 67 setting resource variables for ESX Server 130 134 setting resource variables in a virtual machine 25 67 123 135 139 setting resource variables in ESX Server 21 59 117 shared variables 36 38 73 75 simultaneous connections 22 27 58 60 snapshots checking for existence 30 64 122 snapshots creating 30 63 122 snapshots removing 30 64 122 snapshots reverting 30 64 122 soft power transition 34 71 125 srvany 48 Start method 27 art method 61 arting a virtual machine 27 33 34 1 70 71 119 125 ate of virtual machine 24 64 119 op method 27 op method 61 A An u AW wa opping a virtual machine 27 33 34 61 70 71 119 125 string Skey name 64 keyName 24 Suspend method 28 suspend method 62 suspended machine resuming 27 61 119 125 suspending a virtual machine 28 33 34 62 70 71 94 95 119 125 T TCP port 20 56 Text property 32 time out 110 ToolsLastActive property 25 26 trysoft power transition 34 71
26. Error Codes and Event Logging Error Codes Error Handling for the VmCOM Library 107 108 08 Error Handling for the VmPer Library 08 Common VmCOM and VmPerl Errors 09 Event Logging 1 Using the Event Viewer 1 Reading the Event Log 3 vmware cmd Utility vmware cmd Utility Options md md vmware cmd Operations on a Server vmware cmd Operations on a Virtual Machine Using Symbolic Links Snapshots and Redo Logs Disk Device Names Operations O O O CO O Ou lt powerop mode gt Values N nn N OV vmware cmd Utility Examples Retrieving the State of a Virtual Machine N OV Performing a Power Operation N OV Setting a Configuration Variable N N Connecting a Device 127 VMware ESX Server Resource Variables Index 129 VMware ESX Server System Resource Variables 130 Virtual Machine Resource Variables for ESX Server 135 Using ESX Server Virtual Machine Resource Variables Efficiently 140 Using the Server Object 140 Reusing a Single Server Object 140 141 www vmware com CHAPTER Introduction This release of VMware Scripting APIs version 2 3 comprises two components VmCOM and VmPerl VmCOM is a Component Object Model COM interface for languages such as Microsoft Visual Basic Microsoft Visual Basic Scripting Edition also known as VBScript Mic
27. LIABLE FOR ANY CLAIM DAMAGES OR OTHER LIABILITY WHETHER IN AN ACTION OF CONTRACT TORT OR OTHERWISE ARISING FROM OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE www vmware com CHAPTER 3 Using Sample VmCOM Programs MiniMUI Visual Basic Sample Program The MiniMUI sample program illustrates the use of VmCOM interfaces from a Visual Basic application It is a control panel application allowing users to get status information and to perform power operations on virtual machines registered on a particular server The source code demonstrates how to initialize a server object enumerate virtual machines on a server perform power operations on a virtual machine handle errors and get status information answer a question for a stuck virtual machine To run the program open the project file in Visual Basic The source for the MiniMUI application is in the MiniMUI folder in the VmCOM Scripting API directory The following image shows the application s main window VMware Mini MUI COM Sample Program L a Hostname Username Password sydney bb fmm D _Connect to local server Last operation s status Virtual machine requires user input to continue Registered vitual machines Refresh Configuration fie State v Avms win2000 win2000 vinx off v wms th 2 th72 vmx off v Wwins nt4smpscsighosted nt4smpscsighosted vmx stuck Virtual machine configuratio
28. User s Manual Serror number error_string n elsif power state VM_EXECUTION STATE OFF Spower state VM EXECUTION STATE SUSPENDED print Powering on config n if 1 vm gt start If an error occurs report it and continue my Serror number Serror string Sserver gt get last error print STDERR Could not power on VM Sconfig Error Serror number error_string n else Delay slightly between starting each VM This prevents too much initial load on the server Warning starting many VMs in rapid succession is not recommended sleep 5 Destroys the virtual machine object thus disconnecting from the virtual machine undef vm Destroys the server object thus disconnecting from the server undef Sserver www vmware com 84 CHAPTER 5 Using Sample VmPerl Scripts Checking a Virtual Machine s Power Status You can use a script like the following to determine whether a virtual machine is running suspended or powered off Once you know its power status you can use this information in conjunction with other scripts to start stop or suspend a virtual machine This script status p1 saved with a TXT extension for online viewing can be found on the VMware Web site at www vmware com support developer scripting API doc status pl txt usr bin perl w Copyright C 1998 2004 VMware Inc status pl This script returns the current power
29. VMware GSX Server the host operating system used for this application and VMware ESX Server Getting Support from VMware See www vmware com support developer or full details on the VMware Scripting APIs support policy VMware Scripting API User s Manual What s New in This Release This release of the scripting APIs introduces compatibility with ESX Server 3 The API has changes in several areas to match the feature set of ESX Server 3 The following list summarizes the changes The add_redo and commit operations have been replaced with the new snapshot feature Since ESX Server 3 virtual machines do not support per disk snapshotting new operations are introduced that create and manage snapshots for the virtual machine as a unit The VmPerl API names for the new operations are e VmPerl VM create snapshot name description quiesce memory e VmPerl VM revert to snapshot e VmPerl VM remove snapshot e VmPerl VM has snapshot The same operations are available for the VmCOM API and the vmware cmd utility with similar names Refer to the reference chapters of this manual for more information on these commands Theget pid get remoteconnections get capabilities operations have been removed because they dealt with concepts that do not apply to ESX Server 3 The default port number has changed Whereas the API previously used port 902 by default to connect to ESX Server 2 machines the new default
30. a VmCt1 object assuming the virtual machine is powered off Next set the Guestinfo variable with the VmCOM API Then power on the virtual machine and use the VMware Tools service to retrieve the variable See Sending Information Set in a VmCOM Script to the Guest Operating System on page 37 for an example of this procedure See your server documentation for more information about VMware Tools Guestinfo Variables You pass to the virtual machine variables you define yourself What you pass is up to you but you might find it useful to pass items like the virtual machine s IP address Windows system ID SID for Windows guest operating systems or machine name This is useful in situations where you want to deploy virtual machines on a network using a common configuration file while providing each machine with its own unique identity By providing each virtual machine with a unique identifying string you can use the same configuration file to launch the same nonpersistent virtual disk multiple times in a training or testing environment where each virtual machine would be unique on the network Note that in the case of persistent or undoable disks each virtual disk file must be copied into its own directory if it shares its file name with another virtual disk file When a virtual machine process is created on the server all Guestinfo variables are initially undefined A Guestinfo variable is created the first time it is wr
31. answers as Windows information type events EVENTLOG_INFORMATION_TYPE Each message answer event log begins with a simple string indicating that an answer to a message was received The message answer event log includes the type of message the message text and the answer An example message answer event log string follows Virtual machine received answer Discard D foo vmdk Select an action for the redo log of undoable disk D foo vmdk www vmware com 114 CHAPTER vmware cmd Utility You can use the vmware cmd utility to perform various operations on a virtual machine including registering a virtual machine on the local server getting the power state of a virtual machine setting configuration variables and so on Note The previous vmware control utility is deprecated If you are using scripts with the vmware control utility update your scripts with the new vmware cmd utility or they will not work with VMware GSX Server 2 x or later or with ESX Server 2 x or later By default the vmware cmd utility is installed in the usr bin directory Linux operating system orin C Program Files VMware VMware VmPerl Scripting API Windows operating system 115 VMware Scripting API User s Manual vmware cmd Utility Options The vmware cmd utility takes the following options Option Description H Specifies an alternate host other than the local host If the H option is used then the U
32. configuration file For each virtual dis belonging to the virtual machine the configuration file contains a line identifying the virtual disk file that acts as the backing store for the virtual SCSI disk You use this line to find the numbers belonging to the file name of the virtual disk For example if the configuration file contains the following line scsi0 1 name My VMFS My VM disk 2 vmdk then you know that the disk device name forMy VM disk 2is scsio 1 representing virtual SCSI device 1 on virtual controller 0 of that virtual machine The snapshot feature is implemented These operations are only supported implement redo log functionality Ad VmCOM Objects with several new methods such as CreateSnapshot on ESX Server 3 At the same time the operations that dRedo and Commit are not supported on ESX Server 3 The VmCOM component provides the following objects VmConnectParams VmServerCtl VmcCollection VmCtl VmQuestion 19 VMware Scripting API User s Manual VmConnectParams This object supplies connection information and user credentials to VmServerCt1 Connect or VmCt1 Connect and exposes the properties listed in the following table All VmConnect Params properties allow you to retrieve GET and modify PUT these properties The security for your connection depends upon the security configuration of your VMware server If you re connecting to a VMware server or a virtual ma
33. during this operation as there is no DHCP lease to renew The Start operation always succeeds However if the VMware Tools service is not present or is malfunctioning the running of the script may fail Stop Attempts to shut down the guest operating system and then powers off the virtual machine Reset Attempts to shut down the guest operating system then reboots the virtual machine Suspend Attempts to run a script in the guest operating system that safely disables network connections such as releasing a DHCP lease before suspending the virtual machine VM POWEROP MODE HARD Start Starts or resumes a virtual machine without running any scripts a standard power on or resume Stop reset or suspend Immediately and unconditionally powers off resets or suspends the virtual machine VM_POWEROP_MODE_TRYSOFT Infotype Values First attempts to perform the power transition operation with VM_POWEROP_MODE_SOFT If this fails the same operation is performed with VM_POWEROP_MODE_HARD Sinfotype specifies the product information for the get product info method Infotype Values Description VM_PRODINFO_PRODUCT The VMware product is returned as VmProduct For more information on VmProduct see the following section VM_PRODINFO_PLATFORM The host s operating system is returned as VmPlatform For more information on VmPlatform see VM PRODINFO PLATFORM lt XXX gt Values o
34. find it on the VMware Web site saved with a TXT extension for online viewing at www vmware com support developer scripting API doc sample3 vbs txt VmCOM VBScript Sample Program 3 Copyright c 1998 2004 VMware Inc This program is for educational purposes only It is not to be used in production environments Description This script gets a list of virtual machines registered on the local server It attempts to power on each VM that is not already running and has a line in the config file autostart true Instructions for Windows 2000 and Windows XP host save the contents of this file to a file named sample3 vbs there should be an accompanying file named sample3 wsf t It is placed in the same directory as this file during I product installation This file is responsible for setting b up the Windows Script Host environment and loading the VmCOM type library thereby enabling this script to reference symbolic constants such as vmExecutionState_On in a command line window type t escript nologo sample3 wsf www vmware com CHAPTER 3 Using Sample VmCOM Programs Set connect_params CreateObject VmCOM VmConnect Params By default connects to the local server To connect to a remote server uncomment these lines and set the values appropriately connect_params hostname lt host gt connect_params username lt user gt connect_params password lt p
35. for all virtual machines on a hyperthreaded system The virtual CPUs may freely share packages at any time with any other virtual CPUs none Virtual CPUs in this virtual machine cannot share packages with each other or with virtual CPUs from any other virtual machines internal Applies only to SMP virtual machines Virtual CPUs on a virtual machine may share packages with each other but not with virtual CPUs from other virtual machines cpu max INT Read write Maximum CPU percentage for a virtual machine The valid range of values is 0 to the number representing the total physical CPU resources The maximum may be greater than 100 for SMP virtual machines that may use more than one full physical CPU 136 www vmware com CHAPTER 8 VMware ESX Server Resource Variables Variable Name Variable Type Description cpu min NT Guaranteed minimum CPU percentage reserved for a virtual Read write machine cpu shares NT Number of CPU shares assigned to a virtual machine Read write Memory Statistics mem active NT Amount of memory in KB actively used by a virtual machine mem cpt tgt NT Amount of memory in KB that the virtual machine reads into Note This is not supported in ESX physical memory from its suspend file This matches the Server 3 memory size of the virtual machine or is O zero if the system is not sw
36. from a server where vm name is a string specifying the virtual machine s configuration file name Sserver gt get reso urce sys Retu und em lt variable name gt rns the defined value on success or undef efined value on failure server gt set resou rce sys Retu em lt variable name gt lt value gt rns the defined value on success or undef und Note These methods apply only to ESX Server efined value on failure Gets or sets the value of the ESX Server system resource variable specified by system lt variable name gt For a list of ESX Server system variables see VMware ESX Server System Resource Variables on page 130 59 VMware Scripting API User s Manual VMware VmPerl VM The VMware VmPerl VM object represents a virtual machine running on a particular server You can connect to a virtual machine start stop suspend and resume virtual machines query and modify the configuration file settings and connect and disconnect devices Except where noted otherwise these methods are synchronous the method does not return until it finishes its operation fails or times out Most operations time out after 2 minutes except for power operations which time out after 4 minutes Method Description vm gt connect connectparams vm_name Returns the defined value on success or undef undefined value on failure Establishes a connection with a virtual ma
37. in ESX Amount of memory in MB currently allocated to the VMkernel Disk Statistics system a isk lt HTL gt KBread Total data read in KB for the target SCSI device specified by lt HTL gt system a isk lt HTL gt KBwritten Total data written in KB for the target SCSI device specified by lt HTL gt 132 www vmware com CHAPTER 8 VMware ESX Server Resource Variables Variable Name Variable Type Description system disk lt HTL gt busResets INT Total number of bus resets for the target SCSI device specified by Note This is not supported in ESX lt HTL gt We convert bus and device resets to virtual disk files Server 3 excluding raw devices into aborts so if you compare counters from the virtual machine with this information then they do not always match system disk lt HTL gt cmds INT Total number of commands for the target SCSI device specified by Note This is not supported in ESX lt HTL gt Server 3 system disk lt HTL gt cmdsAborted INT Total number of commands aborted for the target SCSI device Note This is not supported in ESX specified by lt HTL gt We convert bus and device resets to virtual disk Server 3 files excluding raw devices into aborts so if you compare counters from the virtual machine with this information then they do not always match system disk lt HTL gt reads T Total num
38. may break under some environments i It is shown for illustration purposes only Set r new RegExp r pattern undoable disk r ignorecase True Set matches r Execute q text if matches count gt 0 then for i 1 to choices count if choices i Append or choices i Keep then wScript Echo s s gt Automatically selecting amp q choices i amp as answer vm AnswerQuestion q i exit for end if next end if 46 www vmware com CHAPTER 3 Using Sample VmCOM Programs end if WScript Echo s next function State2Str vm select case vm ExecutionState case vmExecutionState_On State2Str ON case vmExecutionState Off State2Str OFF case vmExecutionState_Suspended State2Str SUSPENDED case vmExecutionState_Stuck State2Str STUCK case else State2Str UNKNOWN end select end function The source for the sample program 2 accompanying Windows Script File is in the SampleScripts folder in the VmCOM Scripting API directory You can also find it on the VMware Web site saved with a TXT extension for online viewing at www vmware com support developer scripting AP doc sample2 wsf txt Note If you are using Microsoft Internet Explorer as your browser select View gt Source to view the file Alternately right click this link and download this file lt job id Sample2 gt lt reference object VmCOM Vmctl gt lt script language VBScript src sample2 vbs gt
39. not commit your changes with the vm gt commit method then the redo is automatically committed when the virtual machine is powered off www vmware com CHAPTER 4 Using VmPerl Method Description vm gt commit Sdisk level freeze Swait Returns the defined value on success or undef undefined value on failure Note This method applies only to ESX Server 2 and earlier This method commits the changes in a redo log to a running virtual SCSI disk specified by disk that is associated with the virtual machine specified by vm level can be 0 or 1 When level is 0 there can be one or two redo logs associated with the disk If level is 0 then the top most redo log the redo log being modified is committed to its parent For example if there is currently only the disk vm dsk with a single redo log vm dsk REDO then the changes in vm dsk REDO are committed to vm dsk If a second REDO log vm dsk REDO REDO has been added then the changes in vm dsk REDO REDO are committed to vm dsk REDO level can be 1 only when there are two redo logs associated with the disk vm dsk REDO and vm dsk REDO REDO When level is 1 the changes in the next to top REDO log vm dsk REDO are committed to vm dsk In this case the virtual machine is not frozen while the redo log is being committed Also when the log is committed vm dsk REDO REDO is renamed to vm dsk REDO Sfreeze ca
40. or unknown unknown product type If platform is specified the return value is one of the following windows Microsoft Windows linux Linux operating system or unknown unknown platform type vmware cmd lt vm cfg path gt connectdevice lt device_name gt Connects the specified virtual device to a virtual machine vmware cmd lt vm cfg path gt disconnectdevice lt device_name gt Disconnects the specified virtual device from the virtual machine vmware cmd lt vm cfg path gt getconfigfile Returns a string containing the configuration file name for the virtual machine This method fails if the virtual machine is not connected vmware cmd lt vm cfg path gt getheartbeat Returns the current heartbeat count generated by the VMware Tools service running in the guest operating system The count is initialized to zero when the virtual machine is powered on The heartbeat count is typically incremented at least once per second when the VMware Tools service is running under light load conditions The count stays constant if this service is not running vmware cmd lt vm cfg path gt gettoolslastactive Returns an integer indicating how much time has passed in seconds since the last heartbeat was detected from the VMware Tools service This value is initialized to zero when the virtual machine powers on It stays at zero until the first heartbeat is detected after which the value is always grea
41. powered off virtual machines and resumes suspended virtual machines that have the line autostart true in their configuration files This script includes a slight delay after starting each virtual machine This delay balances the load on the server Do not start many virtual machines in rapid succession without this delay This script startallvms p1 saved with a TXT extension for online viewing can be found on the VMware Web site at wyww vmware com support developer scripting API doc startallvms pltxt usr bin perl w Copyright C 1998 2004 VMware Inc startallvms pl This script powers on all VMs on the system that are not already running usage startallvms pl lt hostname gt lt user gt lt password gt BEGIN if O0 eg MSWin32 INC Set the path to your VmPerl Scripting directory if different C Program Files VMware VMware VmPerl Scripting API perl5 site perl 5 005 C Program Files VMware VMware VmPerl Scripting API per15 site_perl 5 005 MSWin32 x86 use VMware VmPerl use VMware VmPerl VM use VMware VmPerl Server use VMware VmPerl ConnectParams use strict my Sserver name user Spasswd ARGV Change this to specify a port only if needed my Sport undef www vmware com CHAPTER 5 Using Sample VmPerl Scripts Create a ConnectParams object my Sconnect_params VMware VmPerl Connect Params new Sserver_
42. property 26 32 index 66 infoType 25 input requiring 30 32 53 65 66 69 90 93 111 113 114 123 installation VmCOM 14 15 VmPerl 14 15 instsrv 48 insufficient memory 109 insufficient resources 22 27 58 60 109 invalid power transition 109 is_connected method 58 60 ISupportErrorinfo 108 Item property 23 J JScript 42 42 44 K keyName 24 37 38 L limits 22 27 58 60 109 Linux operating system installing VmPerl on 15 list of virtual machines 18 42 44 44 47 47 51 54 80 81 82 84 117 M memory 109 memory size 24 65 122 memory statistics 130 132 137 138 memory values stored in 24 64 messages 111 method VmCOM AddRedo 28 AnswerQuestion 30 32 108 Commit 29 Connect 17 20 22 27 108 109 ConnectDevice 31 CreateSnapshot 30 DisconnectDevice 31 HasSnapshot 30 RegisterVm 22 RemoveSnapshot 30 Reset 28 RevertToSnapshot 30 Start 27 Stop 27 Suspend 28 UnregisterVm 22 method VmPerl add_redo 62 answer_question 66 commit 63 connect 54 58 60 109 connect_device 66 create_snapshot 63 device_is_connected 66 disconnect_device 66 get capabilities 67 get choices 66 69 get config 65 get config file name 64 get connected users 64 get execution state 64 get guest info 64 75 get heartbeat 65 get hostname 56 get id 67 69 get last error 58 60 66 108 get password 57 get pending ques
43. system etc vmware tools vmware guestd cmd info set guestinfo name Sue Williams Retrieving Information in a VmCOM Script With the VmCOM API you use the Guest Info keyName property to retrieve information set in the guest operating system into a VmCOM script running on any machine including GSX Server or any remote workstation that can connect to the virtual machine For example to retrieve Sue s name set by the VMware Tools service query the guest operating system by using the VmCOM API str vm GuestInfo name www vmware com CHAPTER Using Sample VmCOM Programs This section contains sample VmCOM programs written by VMware to demonstrate example uses of the VmCOM API You can modify them to suit the needs of your organization These sample programs are installed with the VmCOM component During installation two folders named MiniMUI and SampleScripts are created in the same directory as the Scripting API The MiniMUI folder contains a sample VmCOM project that you may open with Microsoft Visual Basic 6 The SampleScripts folder contains VBScript and JScript samples using the VmCOM Scripting API Note You may also obtain these sample scripts from the VMware Web site The scripts on the Web site are saved with a TXT extension for online viewing Remove the TXT extension before using these scripts 39 VMware Scripting API User s Manual 40 Copyright Information Each sample script and sample
44. top redo log there must be at least two redo logs of that disk to its The virtual machine is not frozen during the committing process but the script waits until the commit finishes The user can also specify the disk directly as the fifth argument on the command line usage commitnext pl server user password config virtual disk BEGIN if 0 eq MSWin32 INC 5 00503 lib 5 00503 1ib MSWin32 x86 auto 5 00503 1ib MSWin32 x86 site 5 00503 1ib site 5 00503 1ib MSWin32 x86 auto site 5 00503 1ib MSWin32 x86 else push INC usr lib perl5 site perl 5 005 1386 linux usr lib per15 5 00503 LEIO ie use VMware VmPerl use VMware VmPerl Server use VMware VmPerl ConnectParams use VMware VmPerl VM use strict if ARGV 4 amp amp ARGV 5 print Usage 0 server user password path to config file virtual disk n exit 1 my serverName user Spasswd Scfg Sdisk ARGV Use the default port my Sport undef Open up a VM object for the virtual machine associated with the specified config file my Sparams VMware VmPerl ConnectParams new serverName Sport user Spasswd my Svm VMware VmPerl VM new my Serr vm gt connect Sparams cfg if defined Serr www vmware com 104 CHAPTER 5 Using Sample VmPerl Scripts my SerrorNumber SerrorString Svm gt get last error die
45. undef undef Initialize the object for the virtual machine we want to check my Svm VMware VmPerl VM new if vm gt connect Sconnect_params Scfg to check my Serror number Serror string Svm gt get last error die Could not connect to virtual machine at cfg to check An Error Serror number Serror stringn Check to see if the virtual machine is powered on if not end my S vm state Svm gt get execution state if Svm state eq vm constant VM EXECUTION STATE ON Destroys the virtual machine object thus disconnecting from the virtual machine undef vm die The virtual machine cfg_ to check nis not powered on Exiting n Maintain the last read heartbeat value for comparison The heartbeat count begins at zero so a value of 1 ensures at least one comparison my Slast_hb 1 while vm gt is_connected Get the current heartbeat count This should steadily increase as long as VMware tools is running inside the virtual machine my Shb S vm sget_heartbeat unless defined hb www vmware com CHAPTER 5 Using Sample VmPerl Scripts my Serror number Serror string Svm gt get last error die Could not get virtual machine heartbeat n Error Serror number error_string n if hb Slast hb Since we don t have a heartbeat we need to do something H about it Let s shut this virtual machine down and then start the backup virtual
46. vmPowerOpMode_Hard Start Starts or resumes a virtual machine without running any scripts a standard power on or resume Stop reset or suspend Immediately and unconditionally powers off resets or suspends the virtual machine vmPowerOpMode_TrySoft VmProdInfoType First attempts to perform the power transition operation with vmPowerOpMode Soft If this fails the same operation is performed with vmPowerOpMode_Hard VmProdInfoType symbolic constant enumeration specifies the type of product information when reading the Product Info property VmpProdinfoType Values Description vmProdInfo_Product The VMware product type is returned as VmProduct For more information on VmProduct see the following section vmProdInfo_Platform The host platform type is returned as VmPlatform For more information on VmPlatform see VmPlatform on page 35 vmpProdinfo Build The product s build number vmpProdinfo Version Major The product s major version number www vmware com CHAPTER 2 Using VmCOM VmProdInfoType Values Description vmProdinfo Version Minor The product s minor version number vmProdinfo Version Revision The product s revision number VmProduct The VmProduct symbolic constant enumeration denotes a VMware product type The Product Info property returns this information when the requested product information type isvmProdInfo Product
47. vmware cmd lt vm cfg path gt addredo lt disk_device_name gt Note This operation applies only to ESX Server 2 and earlier This operation adds a redo log to a running virtual SCSI disk specified by lt disk_device_name gt that is associated with the virtual machine specified by lt vm cfg path gt Changes made to the virtual disk accumulate in the new redo log This disk must be an ESX Server virtual disk stored on a VMFS volume The format of lt disk_device_name gt is explained in the section Disk Device Names on page 118 The virtual disk can be in persistent undoable or append mode The redo log for a virtual disk in persistent mode uses the file name of the virtual disk with REDO appended to it for example if the disk is called vm dsk the redo log is called vm dsk REDO A virtual disk in undoable or append mode already has a redo log associated with it so the new redo log you create is called vm dsk REDO REDO whose parent is the existing redo log vm dsk REDO This operation fails if the specified virtual disk does not exist the specified virtual disk is in nonpersistent mode an online commit is already in progress or the virtual disk already has two redo logs associated with it Ifyou add a redo log using the vmware cmd addredo command but do not commit your changes with the vmware cmd commit command then the redo is automatically committed when the virtual machine is powered off www vmwar
48. want to display a banner welcoming the student to the class You can pass their name from a VmPerl script to the guest operating system on a student s virtual machine If you have not already done so connect a VMware VmPerl VM object and set the student s name for this virtual machine to Susan Williams Svm gt set_guest_info name Susan Williams This statement passes a string name to the guest operating system You can write a script that reads the string then calls a command specific to the guest operating system to set the student s name in the banner This operation is explained in the following section This setting lasts until you power off the virtual machine and close all connected consoles Retrieving the Information in the Guest Operating System nthe running guest operating system you use the VMware Tools service to retrieve variables set for the virtual machine You can then use this passed name string inside a guest operating system startup sequence Use the following to read the Guestinfo variable key name n a Windows guest operating system VMwareService exe cmd info get guestinfo lt key name gt na Linux guest operating system etc vmware tools vmware guestd cmd info get guestinfo lt key name gt For example to get the current value for the name variable you can type the following in a Linux guest operating system etc vmware tools vmware guestd cmd info g
49. 67 147 get_username method 56 waiting for user input 30 32 44 47 has snapshot method 64 53 65 66 69 90 93 111 113 114 is connected method 58 60 123 register vm method 58 Web proxy 110 registered vm names method 54 Windows operating system installing Scripting APIs on 14 15 Windows Script File 42 44 47 51 58 remove snapshot method 64 reset method 61 revert to snapshot method 64 sample scripts 16 77 100 set config method 65 66 set guest info method 64 74 set resource method 59 67 start method 61 stop method 61 suspend method 62 unregister_vm method 59 use with Linux operating system 7 use with Windows operating system 7 VmPlatform 35 VmPowerOpMode 27 28 33 vmProdInfo_Platform 35 vmProdinfo Product 35 VmpProdInfoType 25 34 VmProduct 35 VmQuestion 30 32 108 VmQuestion Choices 23 VmServerCtl 17 21 22 108 VmServerCtl Connect 20 22 27 VmServerCtl RegisteredVmNames 23 ware Tools 25 26 36 38 65 67 3 75 123 ware VmpPerl ConnectParams 53 56 ware VmPerl Question 53 65 66 ware VmpPerl Server 53 58 59 ware VmPerl VM 53 60 68 73 vmware cmd options 115 server operations 117 virtual machine operations 118 124 vmware control 115 w lt S lt A lt X lt SN lt www vmware com 148
50. Cannot connect to vm Error errorNumber SerrorString n Make the API timeout much larger this is 8 minutes in milliseconds since the commit may take a while Svm gt set_timeout 480000 Commit the next to top REDO log if Svm gt commit disk 1 0 1 my SerrorNumber SerrorString Svm gt get last error die Cannot commit redo log Error errorNumber SerrorString n vm gt disconnect 105 VMware Scripting API User s Manual www vmware com 106 CHAPTER Error Codes and Event Logging This chapter includes information to help you use the VMware Scripting APIs In particular we describe VMware Scripting API errors We also describe how you can use Event Viewer to view and manage event logs for virtual machines on a Windows machine 107 VMware Scripting API User s Manual 108 Error Codes The following sections describe error handling in the VMware Scripting APIs Error Handling for the VmCOM Library VmCOM methods and properties throw error exceptions when they fail VmCOM supports the ISupportErrorInfo interface for detailed error reporting For example in Visual Basic use standard error trapping and examine the err object to retrieve detailed error information The object s Description field contains a string describing the failure The Number field contains a VmCOM error code For more information on VmCOM error codes see Common VmCOM and VmPerl Errors on page 109
51. Finish The VMware Scripting API is installed If you install VmCOM two folders named MiniMUI and SampleScripts are created in the same directory as the VmCOM Scripting API The MiniMUI folder contains a sample Microsoft Visual Basic 6 project that uses VmCOM The SampleScripts folder contains VBScript and JScript samples using the VmCOM Scripting API See Using Sample VmCOM Programs on page 39 for additional information If you install VmPerl a SampleScripts Samples folder is created in the same directory as the VmPerl Scripting API The SampleScripts folder contains sample scripts using the VmPerl Scripting API See Using Sample VmPerl Scripts on page 77 for additional information on the sample scripts At any time you can decide to remove this software from your system by running the installer and selecting the Remove option Alternately use Add Remove Programs in the Control Panel to remove the Scripting API Installing VmPerl Scripting API on a Linux Machine You can install only the VmPerl Scripting API on a Linux machine VmCOM is not supported 1 Copy the VmPerl package to the machine on which you want to run the VMware Scripting API 2 Ina terminal window become root so you can carry out the installation 3 Untar the package tar xzf VMware VmPERLAPI v v v tar gz where v v v is the specific version number and is the build number 4 Change to the directory where you expanded the package cd vmware a
52. I User s Manual www vmware com 52 CHAPTER Using VmPerl The VmPerl interface provides controlled access to VMware servers and virtual machines You can incorporate VmPerl function calls in a Perl script you write to automate the day to day functioning of your server and virtual machines The VmpPerl API consists of four modules or packages VMware VmPerl ConnectParams that provides connection information and authentication user credentials when connecting to a server ware VmPerl Server that controls interaction with a GSX Server or ESX Server machine VI VMware VmPerl VM that controls interaction with a particular virtual machine on a GSX Server or ESX Server VMware VmpPerl Question that provides for user interaction when there is a question or error condition requiring a response VMware VYmPerl Server and VMware VmpPerl VM are the primary modules for communicating with VMware components VMware VmPerl ConnectParams and VMware VmpPerl Question are support modules used as inputs or outputs to the methods and properties of the primary modules A VMware VYmPerl Server object represents a server and exports server level services such as virtual machine enumeration and registration A VMware VmPerl VM object represents a virtual 53 VMware Scripting API User s Manual 54 machine on a particular server and provides virtual machine specific methods including power opera
53. I device 1 on virtual controller 0 of that virtual machine 55 VMware Scripting API User s Manual VMware VmPerl ConnectParams VMware VmPerl ConnectParams new Shostname Sport username Spassword connects to the given hostname and network port and authenticates the connection with the supplied user name and password The VMware VmpPerl ConnectParams module supplies connection information and user credentials to the server gt connect or vm gt connect methods and exposes the methods listed in the following table All VMware VmPerl ConnectParams methods have both read and write permissions allowing you to retrieve GET and set PUT the values The security for your connection depends upon the security configuration of your VMware server If you re connecting to a VMware server or a virtual machine on a VMware server then the connections are encrypted as long as the V ware server is configured to encrypt connections Method Description connectparams gt get hostname Returns the defined value on success or undef undefined value on failure or if the value is not set Set the value and retry the API call connectparams gt set hostname Shostname Sconnectparams gt get_port Returns the defined value on success or undef undefined value on failure or if the value is not set Set the value and retry the API call Sconnectparams gt set_port port Gets or sets the name of a s
54. If a remote virtual machine or server unexpectedly disconnects most operations fail giving you either the vmErr_NOTCONNECTED or vmErr DISCONNECT error code You cannot reconnect to an existing VmCt 1 or VmServerCt1 object Instead destroy the object for example Set obj Nothing in Visual Basic then create a new object and call Connect on it If a virtual machine operation fails with error code vmErr_NEEDINPUT obtain a VmQuestion object from VmCt 1 PendingQuestion property and examine the question or error description Then call AnswerQuestion to answer the question or dismiss the error Error Handling for the VmPerl Library The error codes listed in the following section apply to and can be returned by all of the VmPerl modules When a server method returns an error use server gt get last error ina script to retrieve the error code and optionally its description For example to return an error code anda description of the error in your scripts use my ret string server gt get_last_error Alternately to return only the error code in your scripts use my ret Sserver gt get last error When a vm method returns undef use vm gt get_last_error ina script to retrieve the error code and optionally its description For example to return an error code and a description of the error in your scripts use my ret string S vm gt get last error Alternately to return only the err
55. KB by the virtual adapter specified by lt mac gt This data includes both local virtual machine to virtual machine and remote physical network to ic virtual machine trafi net lt mac gt totKBTx INT Total data transmitted in KB by the virtual adapter specified by lt mac gt This data includes both local virtual machine to virtual machine and remote virtual machine to physical network traffic net lt mac gt totPktsRx INT Total number of packets by the virtual adapter specified by lt mac gt This data includes both local virtual machine to virtual machine and remote physical network to virtual machine traffic net lt mac gt totPktsTx INT Total number of packets transmitted by the virtual adapter specified by lt mac gt This data includes both local virtual machine to virtual machine and remote virtual machine to physical network traffic Other Virtual Machine Statistics worldid INT World ID for a virtual machine pid INT Process ID for a virtual machine uptime INT Uptime in seconds of a running virtual machine 139 VMware Scripting API User s Manual 140 Using ESX Server Virtual Machine Resource Variables Efficiently This section describes how you can query virtual machine variables more efficiently by minimizing overhead Note These tips apply both to both the VmCOM and VmPerl APIs although the examples
56. MATION_TYPE VMware warnings have a warning type and are logged as a Windows warning type event EVENTLOG_WARNING_TYPE VMware errors have a error type and are logged as a Windows error type event EVENTLOG_ERROR_TYPE VMware questions have a question type and are logged as a Windows information type event EVENTLOG_INFORMATION_TYPE Each message event log begins with a simple string indicating that a message was received The message event log includes the type of message and the message text Example message event log strings follow This first example is for a message hint Virtual machine received hint D foo vmx Don t forget to install VMware Tools inside this virtual machine Wait until your guest operating system finishes booting then choose VMware Tools Install from the Settings menu in VMware GSX Server Then follow the instructions that are provided Ok This second example is for an error message Virtual machine received error D foo vmx Failed to resume disk ide0 0 The disk was modified since the virtual machine was suspended 113 VMware Scripting API User s Manual Error encountered while trying to restore ide0 0 state from file foo vmss OK This third example is for a question Virtual machine received question D foo vmdk Select an action for the redo log of undoable disk D foo vmdk Commit Discard Keep Message Answers The Event Viewer logs message
57. O REDO is renamed to vm dsk REDO lt freeze gt can be 0 or 1 If lt freeze gt is 0 then the virtual machine is not frozen when changes are committed though it runs more slowly If lt freeze gt is 1 then the virtual machine is frozen until the commit operation finishes If lt level gt is 0 then the virtual machine must be frozen when changes are committed and lt freeze gt is ignored lt wait gt can be 0 or 1 If lt wait gt is 0 then the method returns as soon as the commit begins If lt wait gt is 1 then the method does not return until the commit completes The method fails if the specified virtual disk does not exist the specified virtual disk is in nonpersistent mode an online commit is already in progress or the virtual disk currently has no redo logs 29 VMware Scripting API User s Manual 30 Method Description object CreateSnapshot lt name gt lt description gt lt quiesce gt lt memory gt Note This method applies only to ESX Server 3 This method creates a snapshot of the virtual machine lt name gt is a user defined string value used as a non unique identifier for the snapshot lt description gt is a string describing the snapshot lt quiesce gt can be 0 or 1 If lt quiesce gt is 0 then the snapshot is taken immediately If lt quiesce gt is 1 and the virtual machine is powered on when the snapshot is taken VMware Tools is used to quiesce the fi
58. S IN THE SOFTWARE 79 VMware Scripting API User s Manual 80 Listing the Virtual Machines on the Server You can use a script like the following to generate a list of all the registered virtual machines on a server You need to know the name of the machine and you must provide a valid user name and password to connect to the server This script enumerate p1 saved with a TXT extension for online viewing can be found on the VMware Web site at www vmware com support developer scripting APl doc enumerate pl txt usr bin perl w Copyright C 1998 2004 VMware Inc enumerate pl This script lists all of the registered virtual machines on the server specified by hostname usage enumerate pl lt hostname gt lt user gt lt password gt HHH H HHH HH BEGIN if O eq MSWin32 INC Set the path to your VmPerl Scripting directory if different C Program Files VMware VMware VmPerl Scripting API perl15 site perl 5 005 C Program Files VMware VMware VmPerl Scripting API per15 site_perl 5 005 MSWin32 x86 use VMware VmPerl use VMware VmPerl Server use VMware VmPerl ConnectParams use strict my Sserver name user Spasswd ARGV Use the default port Change this if you need to specify the port my Sport undef Create a new VMware VmPerl Server to connect to the server To connect to the remote server use the following line www vmware co
59. SS mma mm m mememmmm m mmm m m m lt E_BADSTATE 66 109 E_BADVERSION 109 DISCONNECT 109 _INSUFFICIENT_RESOURCES _INVALIDARGS 109 _INVALIDVM 109 EEDINPUT 109 ETFAIL 109 OACCESS 109 OMEM 109 OPROPERTY 109 OSUCHVM 110 OTCONNECTED 110 OTSUPPORTED 110 ROXYFAIL 110 EOUT 110 lebel NSPECIFIED 110 MBUSY 110 MEXISTS 110 NITFAILED 110 ESX Server 21 59 117 CPU statistics 130 disk statistics 132 memory statistics 130 132 get_heartbeat method 65 get_hostname method 56 get_id method 67 69 get_last_error method 58 60 66 108 get_password method 57 get_pending_question method 65 get_pid method 67 get_port method 56 get_product_info method 65 71 72 get_remote_connections method 67 get_resource method 59 67 get_text method 65 69 get_tools_last_active method 65 67 get_uptime method 67 get_username method 56 getting resource variables for ESX Server 21 59 117 130 134 getting resource variables in a virtual machine 25 67 123 135 139 guest operating system 26 36 38 67 73 75 uptime 25 67 123 Guestinfo property 24 Guestinfo variable 36 38 73 75 122 H hard power transition 34 71 125 www vmware com has_snapshot method 64 HasSnapshot method 30 heartbeat 25 65 87 89 123 Heartbeat property 25 host platform 35 72 123 hostname 20 56 l ID for a running virtual machine 26 67 123 Id
60. Server 2 x supports a maximum of 200 registered virtual machines per server 21 VMware Scripting API User s Manual 22 Method Description object Connect lt params gt The Connect method connects the object to a VMware GSX Server or VMware ESX Server where params is a VmConnect Params object that specifies the system and user information There is no method to disconnect from a server To reconnect to a different server destroy the VmServerCt 1 object create a new one then call its Connect method The total number of connected VmCt 1 and VmServerCt1 objects cannot exceed 62 The Connect method fails with error code vmeErr_INSUFFICIENT_RESOURCES if this limit is reached In order to connect new objects destroy one or more connected VmCt 1 or VmServerCt1 objects For example you can do this by setting an object to Nothing in Visual Basic object RegisterVm lt vmName gt The RegisterVm method registers a virtual machine on a server where vmName is a string specifying the virtual machine s configuration file name object UnregisterVm lt vmName gt The UnRegisterVm method unregisters a virtual machine from a server where vmName is a string specifying the virtual machine s configuration file name www vmware com CHAPTER 2 Using VmCOM VmCollection The VmCollection object is a collection of variants that are typically strings You can enumerate its elements by using the fo
61. TATE ON state vm gt reset mode Returns the defined value on success or undef undefined value on failure Shuts down then reboots a virtual machine where mode specifies the operation s behavior based on the value of the VMware VmPerl VM POWEROP MODE lt XXX gt where lt XXX gt is HARD SOFT or TRYSOFT If mode is not specified the default mode is VM_POWEROP_MODE_SOFT See VM POWEROP MODE lt XXX gt Values on page 70 Note If you are connecting to GSX Server 1 x or ESX Server 1 x then you must specify VMware VmPerl VM POWEROP MODE HARD as the mode or the operation will fail This method always fails if the virtual machine is not in the VM EXECUTION STATE ON state 61 VMware Scripting API User s Manual 62 Method Description vm gt suspend mode Returns the defined value on success or undef undefined value on failure Suspends a virtual machine where mode specifies the operation s behavior based on the value of the VMware VmPerl VM_POWEROP_MODE_ lt XXX gt where lt XXX gt is HARD SOFT or TRYSOFT It saves the current state of the virtual machine to a suspend file If mode is not specified the default mode is VM_POWEROP_MODE_SOFT For more information see VM_POWEROP_MODE_ lt XXX gt Values on page 70 Note If you are connecting to GSX Server 1 x or ESX Server 1 x then you must specify VMware VmPerl VM_POWEROP_MODE_HARD as the mode or the operation will fail
62. VERSION 2 3 VMware Scripting API User s Manual L_ a a m T 0 DOIDO B88 L Bea ETES TESTES TESTE E LJ E O z 0 Beeb B nam Ea O saladas VMware Inc 3145 Porter Drive Palo Alto CA 94304 www vmware com eee of Please note that you can always find the most up to date technical documentation on our Web site at http www vmware com support The VMware Web site also provides the latest product updates Copyright 1998 2006 VMware Inc All rights reserved Protected by one or more of U S Patent Nos 6 397 242 6 496 847 6 704 925 6 711 672 6 725 289 6 735 601 6 785 886 6 789 156 6 795 966 6 880 022 6 961 941 6 961 806 and 6 944 699 patents pending VMware the VMware boxes logo and design Virtual SMP and VMotion are registered trademarks or trademarks of VMware Inc in the United States and or other jurisdictions All other marks and names mentioned herein may be trademarks of their respective companies Revision 20060925 Item SDK ENG Q306 114 Table of Contents
63. a Virtual Machine The following examples illustrate retrieving the execution state of a virtual machine Change directories to the directory folder containing the vmware cmd utility or include the full path to the utility when typing the following on a command line Note that you must use double quotes when specifying a path with spaces for example C Program Files VMware VMware VmPerl Scripting API vmware cmd In a Linux guest operating system vmware cmd home vmware win2000 vmx getstate where home vmware win2000 vmx is the path to the virtual machine s configuration file In a Windows guest operating system vmware cmd C home vmware win2000 vmx getstate where C home vmware win2000 vmx is the path to the virtual machine s configuration file Performing a Power Operation The following examples illustrate performing a power operation The first example illustrates powering on a virtual machine and the second example illustrates performing a hard reset Change directories to the directory folder containing the vmware cmd utility or include the full path to the utility when typing the following on a command line Note that you must use double quotes when specifying a path with spaces for example C Program Files VMware VMware VmPerl Scripting API vmware cmd In a Linux guest operating system vmware cmd v home vmware win2000 vmx start where v indicates the verbose option home vmware win2000 vmx is the path
64. a path with spaces for example C Program Files VMware VMware VmPerl Scripting API vmware cmd vmware cmd D foo vmx connectdevice ide1 0 where D foo vmx is the virtual machine s configuration file and ide1 0 is the device name 127 VMware Scripting API User s Manual www vmware com 128 CHAPTER VMware ESX Server Resource Variables This chapter includes ESX Server resource variables that you can set on ESX Server and on virtual machines running on ESX Server You can get and set these resource variables through the VmCOM resource property and the VmPerl get_resource and set_resource methods 129 VMware Scripting API User s Manual 130 VMware ESX Server System Resource Variables Use these variables to return or set s atistics on ESX Server For more information on the VmCOM resource property see VmServerCt on page 21 For more information on the VmPerl get resourceand set resource methods see VMware VmPerl Server on page 58 In the following table represents t has four physical CPUs then is 0 1 he number for a particular CPU For example if an ESX Server 2 013 lt HTL gt represents the host target LUN for a SCSI device For example for vmhba1 2 0 1 represents the host adapter 2 represents the target on the adapter and 0 specifies the LUN lt vmnic gt represents the physical ne work interface card for example vmnico Variable Name Variable Type De
65. add a redo log using the AddRedo method but do not commit your changes with the Commit method then the redo is automatically committed when the virtual machine is powered off www vmware com CHAPTER 2 Using VmCOM Method Description object Commit lt diskDevName gt lt level gt lt freeze gt lt wait gt Note This method applies only to ESX Server 2 and earlier This method commits the changes in a redo log to a running virtual SCSI disk specified by lt diskDevName gt that is associated with the virtual machine specified by vm lt level gt can be 0 or 1 When lt level gt is 0 there can be one or two redo logs associated with the disk If lt level gt is 0 then the top most redo log the redo log being modified is committed to its parent For example if there is currently only the disk vm dsk with a single redo log vm dsk REDO then the changes in vm dsk REDO are committed to vm dsk If a second REDO log vm dsk REDO REDO has been added then the changes in vm dsk REDO REDO are committed to vm dsk REDO lt level gt can be 1 only when there are two redo logs associated with the disk vm dsk REDO and vm dsk REDO REDO When lt level gt is 1 the changes in the next to top REDO log vm dsk REDO are committed to vm dsk In this case the virtual machine is not frozen while the redo log is being committed Also when the log is committed vm dsk RED
66. always succeeds However if VMware Tools is not present or is malfunctioning the VMware Tools to be installed and running of the script may fail running in the guest operating Start when virtual machine is powered off After powering on the virtual machine it system attempts to run a script in the guest operating system when the VMware Tools service becomes active The default script does nothing during this operation as there is no DHCP lease to renew The Start operation always succeeds However if VMware Tools is not present or is malfunctioning the running of the script may fail Stop Attempts to shut down the guest operating system and then powers off the virtual machine Reset Attempts to shut down the guest operating system then reboots the virtual machine Suspend Attempts to run a script in the guest operating system before suspending the virtual machine hard Start Starts or resumes a virtual machine without running any scripts a standard power on or resume Stop reset or suspend Immediately and unconditionally powers off resets or suspends the virtual machine trysoft First attempts to perform the soft power transition operation If this fails the hard power operation is performed 125 VMware Scripting API User s Manual 126 vmware cmd Utility Examples This section includes examples of using the vmware cmd utility on a virtual machine Retrieving the State of
67. and P options must also be specified O Specifies an alternative port The default port number for ESX Server 3 x is 443 the default port number for ESX Server 2 x and other VMware products is 902 U Specifies the username P Specifies the user s password h Prints a help message listing the options for this utility q Turns on the quiet option with minimal output The specified operation and arguments are not specified in the output v Turns on the verbose option www vmware com 116 CHAPTER 7 vmware cmd Utility vmware cmd Operations on a Server The syntax for this utility on a server is vmware cmd s lt options gt lt server operation gt lt arguments gt The vmware cmd utility performs the following operations on a VMware server Server Operation Description vmware cmd l Lists the virtual machines on the local server Unlike the other server operations this option does not require the s option vmware cmd s register lt vm cfg path gt Registers a virtual machine specified by lt vm cfg path gt on the server vmware cmd s unregister lt vm cfg path gt Unregisters a virtual machine specified by lt vm cfg path gt on the server vmware cmd s getresource lt vm cfg path gt lt variable_name gt Note These methods apply only to ESX Server Gets the value of the ESX Server system resource variable specified by system lt variable_name gt For a l
68. apping from the virtual machine s suspend file mem cptread INT Size in KB of the suspend file for a virtual machine that has Note This is not supported in ESX been read into memory If the system memory is low the Server 3 suspend file is used as a special swap file for the VMkernel when the virtual machine is resumed mem mctltgt INT The VMkernel believes this is the size in KB of the vmmemct 1 balloon driver in the guest operating system for a virtual machine This value should approach mem memctl next row in this table mem memctl NT Amount of reclaimed memory in KB after running the vmmemct 1 module for a virtual machine mem overhd NT Overhead memory in KB for a virtual machine mem ovhdmax NT Maximum overhead memory in KB for a virtual machine mem shared NT Amount of memory in KB that is shared through transparent page sharing either within a virtual machine or with other virtual machines running on the same server mem size NT Size of the actual memory in KB for a virtual machine This value should approach mem sizetgt next row in this table mem sizetgt NT Target memory size in KB for a virtual machine Note This is not supported in ESX Server 3 mem swapin NT KB swapped into memory since the last time the virtual machine was booted mem swapout NT KB swapped out to disk since the last time the virtual machine was booted mem swapped NT Amount of memory in KB swapped in and out to the VMFS partit
69. assword gt And use this if your port number is different connect_params port 902 Set vm server CreateObject VmCOM VmServerCt1 Handle errors non fatally from here on On Error Resume Next Try connecting to server a few times It s possible the VMware services are still in the process of starting up We ll wait a maximum of 12 10 120 seconds 2 minutes 1 connected false for tries 1 to 12 vm server Connect connect params if Err number 0 then connected true exit for end if WScript Echo Could not connect to server amp Err Description WScript Echo Retrying in 10 seconds WScript Sleep 10000 Err clear next if not connected then WScript Echo Failed to connect to server Giving up WScript Quit end if Get a list of all VMs from the server Set vmlist vm_server RegisteredVmNames for each config in vmlist Connect to the VM Set vm CreateObject VmCOM VmCt1 49 VMware Scripting API User s Manual vm Connect connect params config if Err Number lt gt 0 then WScript Echo Could not connect to VM amp config amp amp Err Description Err Clear else Check that the VM should be started automatically auto_start vm Config autostart if Err Number lt gt 0 then if Err Number lt gt vmErr NOPROPERTY then WScript Echo Could not read autostart variable amp Err Number amp amp Err Description else WScript Echo This VM is not conf
70. at 25 d 26 32 tem 23 PendingQuestion 24 30 32 108 Pid 25 Productinfo 25 RegisteredVmNames 21 RemoteConnections 26 Resource 21 25 Text32 ToolsLastActive 25 26 Uptime 25 proxy 110 proxy failure 110 Q question 53 65 66 69 90 93 111 113 114 123 R reconnect to a virtual machine 27 redo log 28 44 62 101 120 redo log committing changes to 29 63 103 121 register_vm method 58 registered_vm_names method 54 58 RegisteredVmNames property 21 registering virtual machine 58 110 117 RegisterVm method 22 RemoteConnections property 26 remove_snapshot method 64 RemoveSnapshot method 30 removing snapshots 30 64 122 Reset method 28 reset method 61 www vmware com resetting a virtual machine 28 33 34 61 70 71 119 125 Resource property 21 25 resource variable 129 139 get 21 25 59 67 117 123 set 21 25 59 67 117 123 resuming a suspended machine 27 61 119 125 revert_to_snapshot method 64 reverting snapshots 30 64 122 RevertToSnapshot method 30 S sample scripts VmCOM 15 39 51 connecting to server and listing vir tual machines 42 44 44 47 listing and starting virtual machines 47 51 sample scripts VmPerl 77 100 answering question for stuck virtual machine 90 93 determining power status 85 86 listing and starting virtual machines 82 84 listing virtual machines 80 81 monitoring virtual machine heart beat 87 89 retrieving a configuration variable
71. ate On return ON break case vmExecutionState Off return OFF break case vmExecutionState_Suspended return SUSPENDED break case vmExecutionState Stuck return STUCK break default return UNKNOWN break The source for the sample program 1 accompanying Windows Script File is in the SampleScripts folder in the VmCOM Scripting API directory You can also find it on the VMware Web site saved with a TXT extension for online viewing at www vmware com support developer scripting API doc sample 1 wsf txt Note Ifyou are using Microsoft Internet Explorer as your browser select View gt Source to view the file Alternately right click this link and download this file lt job id Samplel gt lt reference object VmCOM Vmctl gt lt script language JScript src samplel js gt lt job gt VBScript Sample Program 2 This VBScript sample program 2 provides similar functionality to sample program 1 It also connects to the local server and lists all registered virtual machines If a virtual machine is in the stuck state the pending question is displayed In addition sample program 2 also illustrates how to handle a virtual machine that is waiting for input to a question that is the virtual machine is in the vmExecutionState_Stuck state For example if a virtual machine is configured with an undoable disk and a redo log is found this www vmware com CHAPTER 3 Using Sample VmCOM Programs
72. ation purposes only Instructions for Windows 2000 and later operating systems save the contents of this file to a file named sample2 vbs unless it s already named that way there should be an accompanying file named sample2 wsf l It is placed in the same directory as this file during i product installation This file is responsible for setting i up the Windows Script Host environment and loading the VmCOM type library thereby enabling this script to reference symbolic constants such as vmExecutionState_On 45 VMware Scripting API User s Manual 1 in a command line window type cscript nologo sample2 wsf Set cp CreateObject VmCOM VmConnect Params Set s serve erver CreateObject VmCOM VmServerCt1 r Connect cp Set vmCollection server RegisteredvmNames for e Se ach vmName in vmCollection t vm CreateObject VmCOM Vmct1 vm Connect cp vmName s if path amp vmName amp state amp State2Str vm amp os amp vm Config guestos vm ExecutionState vmExecutionState Stuck then Set q vm PendingQuestion Set choices q choices s s amp question amp q text amp choices for each choice in choices s s amp amp choice amp next If this looks like an undoable disk save question automatically answer Append or Keep 1 NOTE this code makes a lot of assumptions about the product and the language used and
73. ber of reads for the target SCSI device specified by lt HTL gt system disk lt HTL gt writes T Total number of writes for the target SCSI device specified by lt HTL gt Network Statistics system net lt device gt totKBRx T Total amount of data received in KB on the virtual switch attached o lt device gt This data includes both local virtual machine to virtual machine and remote physical network to virtual machine traffic system net lt device gt totKBTx T Total amount of data transmitted in KB on the virtual switch attached to lt device gt This data includes both local virtual machine o virtual machine and remote virtual machine to physical network raffic system net lt device gt totPktsRx INT Total number of packets received on the virtual switch attached to lt device gt This data includes both local virtual machine to virtual machine and remote physical network to virtual machine traffic Note In releases prior to ESX Server 2 1 1 there may be inconsistencies when non unicast packets broadcasts multicasts and unicasts to virtual NICs in promiscuous mode are received system net lt device gt totPktsTx INT Total number of packets transmitted on the virtual switch attached to lt device gt This data includes both local virtual machine to virtual machine and remote physical network to virtual machine traffic Note In releases prior to ESX Server 2 1 1 there may be inconsistencies when non unicast packets are
74. ch syntax in Visual Basic If you know the configuration file name of a specific virtual machine you can connect the VmCt 1 object directly without using a VmServerCt1 object You can use languages such as Visual Basic or Visual C to access VmCOM components For example to use VmCOM from Visual Basic choose Project gt References and enable the check box for VMware VmCOM lt version gt Type Library If this entry is not present verify that the VMware product is installed correctly To use VmCOM from another language refer to the documentation for that language Look for the section in the documentation that describes ActiveX components or the COM interface for that language Using Symbolic Links Many Scripting API operations require you to supply a path to a virtual machine used in the operation The Scripting API does not support using symbolic links to refer to virtual machine configuration paths on remote hosts with ESX Server 3 installed Scripts that try to open virtual machines using symbolic links will fail with an error When using the Scripting API remotely with ESX Server 3 identify virtual machines with their absolute UUID based path or their datastore path For example a path that uses a UUID might look like this vm s volumes 19496567 9ac80b57 testVM vm1 vmx Alternatively the same virtual machine can be opened using a datastore path that might look like this mystorage test VM vm1 vmx Both of these c
75. chine on a server then the connections is encrypted as long as the VMware server is configured to encrypt connections Property Name Property Type Access Type Description Hostname Port string integer GET PUT GET PUT Retrieves and sets the name of a server where Hostname is the server s hostname or IP address If Hostname is not given or undefined the authentication is performed on the local system The C library connects to the local host and uses current user information when it connects However this user information is not passed back to VmConnect Params Otherwise you may supply the user name and password for authentication as that user Retrieves and sets the TCP port to use when connecting to the server Its default value is O zero indicating the default port number should be used Otherwise enter the correct port number A port number set to a negative value is treated as an incorrect value and the default port number is used instead Note The default port number for ESX Server 3 x is 443 the default port number for ESX Server 2 x and other VMware products is 902 If your script connects to ESX Server 3 x and to other products or versions as well we recommend that you supply a value of 0 zero for the port number which allows the server port number to be selected automatically Username string GET PUT Retrieves and sets the name of a user on the server Password
76. chine using the specified parameters where Sconnectparams specifies the system and user information and vm_name is a string specifying the virtual machine s configuration file name The total number of connected VMware VYmPerl VM and VMware VYmpPerl Server objects cannot exceed 62 The connect method fails with error code VM E INSUFFICIENT RESOURCES if this limit is reached In order to connect new objects destroy one or more connected VMware VYmpPerl VM or VMware VmPerl Server objects vm gt get last error Returns the error code and descriptive string Gets details about the last error that occurred in an array of form Serror_num Serror_string vm gt is_connected Returns the defined value on success or undef undefined value on failure if the virtual machine is not connected or if there is a failure You can use vm gt get_last_error to determine if an error occurred or if the virtual machine is not connected Use this method to determine whether or not a connection exists to the virtual machine specified by vm The remaining methods only work after you connect to the virtual machine with Sym gt connect Note The following table includes some ESX Server specific methods and are specifically noted www vmware com CHAPTER 4 Using VmPerl Method Description vm gt start mode Returns the defined value on success or undef undefined value on failure
77. corrupted or improperly formatted vmErr NEEDINPUT VM E NEEDINPUT The operation did not complete because the virtual machine is stuck and waiting for user input that is the user must answer a question or acknowledge an error before the virtual machine can continue its operation vmeErr_NETFAIL VM_E_NETFAIL A network failure or misconfiguration prevented the operation from completing vmeErr_NOACCESS VM_E_NOACCESS The operation could not be completed because of an access violation a permissions problem vmeErr_NOMEM VM_E_NOMEM Your system has run out of memory Shut down some processes to free up memory vmErr NOPROPERTY VM E NOPROPERTY The requested variable or property name does not exist 109 VMware Scripting API User s Manual 110 VmCOM Error Code VmPerl Error Code Description VmErr_NOSUCHVM VM_E_NOSUCHVM The specified virtual machine configpration file does not exist The path to the configuration file may have been entered incorrectly or the virtual machine is not registered vmErr_NOTCONNECTED VM_E_NOTCONNECTED An operation was attempted on a disconnected virtual machine Connect the virtual machine before performing this operation vmErr_NOTSUPPORTED VM_E_NOTSUPPORTED The attempted operation is not supported by your version of VMware server vmErr PROXYFAIL VM E PROXYFAIL The Scripting API could not connect to the serv
78. de example illustrates connecting a virtual drive to a CD image file Svm gt set_config idel 0 devicetype cdrom image vm gt set_config idel 0 filename iso foo iso Svm gt connect_device idel 0 Svm gt disconnect_device Sdev_name Returns the defined value on success or undef undefined value on failure Sets a virtual device to the disconnected state where dev_name isa string identifying the virtual device you want to disconnect The virtual machine must be powered on for this method to succeed otherwise a VM_E_BADSTATE error is returned 66 www vmware com Method Description vm gt get_resource lt variable name gt Returns the defined value on success or undef undefined value on failure vm gt set resource lt variable_name gt lt value gt Returns 1 on success or undef undefined value on failure Note These methods apply only to ESX Server Gets or sets the value of the virtual machine resource variable specified by lt variable_name gt For a list of virtual machine resource variables see Virtual Machine Resource Variables for ESX Server on page 135 vm gt get_uptime Note This method does not apply to ESX Server 3 Accesses the uptime of the guest operating system on the virtual machine vm gt get_id Returns a unique ID for a running virtual machine vm gt get_pid Note This method does not appl
79. e Using VmPerl to Pass User Defined Information Between a Running Guest Operating System and a Script on page 73 This script Saveguestip pl formerly known as configsetip pl saved with a TXT extension for online viewing can be found on the VMware Web site at www vmware com support developer scripting API doc saveguestip pl txt usr bin perl w Copyright C 1998 2004 VMware Inc saveguestip pl This script demonstrates the use of the VMware guest service to set a configuration variable from within a running virtual machine s guest operating system It stores the guest operating system s IP address The host can retrieve the IP address with a corresponding script usage saveguestip pl NOTE This script should be run from within a running virtual machine s guest operating system The corresponding script getguestip pl can be run from the host operating system if ARGV 0 print Usage 0 n exit 1 www vmware com CHAPTER 5 Using Sample VmPerl Scripts my Serr Get the IP for the Guest my ip undef Sip amp get_ip if defined ip die 0 Could not get guest ip n else print 0 guest ip is ip n Sets the ip address configuration variable Serr amp set ip variable if err 0 die 0 Could not set guest ip n Captures IP address from the OS sub get_ip my myip iparr
80. e VYmpPerl ConnectParams 56 VMware VYmpPerl Server 58 VMware VYmpPerl VM 60 Additional Information on get tools last active 67 VMware VYmpPerl Question 69 Symbolic Constants 70 VM EXECUTION STATE lt XXX gt Values 70 VM POWEROP MODE lt XXX gt Values 70 Infotype Values 71 VM_PRODINFO_PRODUCT_ lt XXX gt Values he VM_PRODINFO_PLATFORM_ lt XXX gt Values 72 Using VmPerl to Pass User Defined Information Between a Running Guest 73 Operating System and a Script GuestInfo Variables 73 Sending Information Set in a VmPer Script to the Guest Operating System 74 Sending Information Set in the Guest Operating System to a VmPerl Script 74 www vmware com Using Sample VmPerl Scripts Copyright Information 77 79 Listing the Virtual Machines on the Server 80 Starting All Virtual Machines on a Server 82 Checking a Virtual Machine s Power Status 85 87 Monitoring a Virtual Machine s Heartbeat Answering Questions Posed by a Virtual Machine Suspending a Virtual Machine 90 94 Setting a Virtual Machine s IP Address Configuration Variable Getting a Virtual Machine s IP Address 96 99 Adding a Redo Log to a Virtual Disk ESX Server 2 x only 101 Committing a Redo Log to a Virtual Disk without Freezing the Virtual Machine 103 ESX Server 2 x only
81. e com CHAPTER 7 vmware cmd Utility Virtual Machine Operation Description vmware cmd lt vm cfg path gt commit This method commits the changes in a redo log to a running virtual SCSI disk lt disk_device_name gt lt level gt lt freeze gt specified by lt disk_device_name gt that is associated with the virtual machine lt wait gt specified by lt vm cfg path gt The format of lt disk_device_name gt is explained Note This operation applies only to ESX in the section Disk Device Names on page 118 Server 2 and earlier lt level gt can be 0 or 1 When lt level gt is 0 there can be one or two redo logs associated with the disk If lt level gt is 0 then the top most redo log the redo log being modified is committed to its parent For example if there is currently only the disk vm dsk with a single redo log vm dsk REDO then the changes in vm dsk REDO are committed to vm dsk If a second REDO log vm dsk REDO REDO has been added then the changes in vm dsk REDO REDO are committed to vm dsk REDO lt level gt can be 1 only when there are two redo logs associated with the disk vm dsk REDO and vm dsk REDO REDO When lt level gt is 1 the changes in the next to top REDO log vm dsk REDO are committed to vm dsk In this case the virtual machine is not frozen while the redo log is being committed Also when the log is committed vm dsk REDO REDO is renamed to vm dsk REDO lt freez
82. e gt can be 0 or 1 If lt freeze gt is 0 then the virtual machine is not frozen when changes are committed though it runs more slowly If lt freeze gt is 1 then the virtual machine is frozen until the commit operation finishes If lt level gt is 0 then the virtual machine must be frozen when changes are committed and lt freeze gt is ignored lt wait gt can be 0 or 1 If lt wait gt is 0 then the method returns as soon as the commit begins If lt wait gt is 1 then the method does not return until the commit completes The method fails if the specified virtual disk does not exist the specified virtual disk is in nonpersistent mode an online commit is already in progress or the virtual disk currently has no redo logs 121 VMware Scripting API User s Manual 122 Virtual Machine Operation Description vmware cmd lt vm cfg path gt createsnapshot lt name gt lt description gt lt quiesce gt lt memory gt Note This operation applies only to ESX Server 3 This operation creates a snapshot of the virtual machine specified by lt vm cfg path gt lt name gt is a user defined string value used as a non unique identifier for the snapshot lt description gt is a string describing the snapshot lt quiesce gt can be 0 or 1 If lt quiesce gt is 0 then the snapshot is taken immediately If lt quiesce gt is 1 and the virtual machine is powered on when the snapshot is taken VMware T
83. e path For example a path that uses a UUID might look like this vmfs volumes 19496567 9ac80b57 testVM vml vmx Alternatively the same virtual machine can be opened using a datastore path that might look like this mystorage testVM vm1 vmx Both of these configuration file path formats can be used anywhere a configuration path is required UUID and datastore formats can be used interchangeably For more information on path format specifications refer to the VMware Infrastructure SDK Programming Guide Snapshots and Redo Logs ESX Server 3 introduces the concept of snapshots to the Scripting API Prior to ESX Server 3 it was possible to roll back virtual machine disk state to a designated point by using redo logs on a per disk basis With ESX Server 3 virtual machine state can be captured as a whole in a snapshot which optionally includes the memory state of a running virtual machine The snapshot feature is implemented with several new operations such as createsnapshot These operations are only supported on ESX Server 3 At the same time the operations that implement redo log functionality addredo and commit are not supported on ESX Server 3 Disk Device Names For certain operations you need to specify a virtual disk Virtual disks are specified from the perspective of the virtual machine using the virtual controller number and the virtual SCSI device number The disk device name is a string in the format scsi lt m gt
84. e virtual machine we want to check my vm VMware VmPerl VM new my vm_ok vm gt connect Sconnect_params Scfg unless Svm ok my Serr Serrstr Svm gt get last error undef vm die Could not connect to vm error Serr Serrstr n Check the power state of the virtual machine If it s stuck get the question and list the possible responses my S state Svm gt get execution state if defined state my Serr Serrstr Svm gt get last error Destroys the virtual machine object thus disconnecting from the virtual machine undef vm die Could not get execution state of vm error Serr Serrstr n if state ne VM_EXECUTION STATE STUCK print There is no question to answer n else my q vm gt get pending question unless defined q undef vm die Could not get the pending question n my text Sq gt get text unless defined Stext undef vm die Could not get the text of the pending question n my choices q gt get_choices unless defined choices 0 undef vm die Could not get the choices to answer the pending question in Print question and choices for user print in q gt get_text n 91 VMware Scripting API User s Manual 92 my Sanswer do prompt choices Sanswer get_answer until valid answer Sanswer choices my Sop_ok Sop ok vm gt answer_question q Sanswer 1
85. ect that represents the question that requires an answer and choice represents the index of the selected answer to the question The index is an integer and the first choice s index is always 1 one The second choice s index is 2 and so on When a virtual machine is in the vmExecutionState_Stuck state and requires user input to continue use this method to answer the current question or dismiss the current error message First get a VmQuest ion object from vmCt1 PendingQuestion You can retrieve the possible choices and their respective indices from the VmQuestion Choices property Then use the AnswerQuestion method to answer the question www vmware com CHAPTER 2 Using VmCOM Method Description object ConnectDevice lt devName gt The ConnectDevice method sets a virtual device to the connected state where devName is a string that identifies the virtual device you want to connect The virtual machine must be powered on for this method to succeed otherwise a vmErr BADSTATE error is returned Usethe Config property to set configuration parameters relevant to the virtual device before calling the ConnectDevice method The following code example illustrates connecting a virtual drive to a CD image file vm Config idel 0 devicetype cdrom image vm Config idel 0 filename iso foo iso vm ConnectDevice idel 0 object DisconnectDevice lt devName gt The DisconnectDevice m
86. ected Heartbeat integer GET Returns the current heartbeat count generated by the VMware Tools service running in the guest operating system The count is initialized to zero when the virtual machine is powered on The heartbeat count is typically incremented at least once per second when the VMware Tools service is running under light load conditions The count stays constant if this service is not running ToolsLastActive integer GET Returns an integer indicating how much time has passed in seconds since the last heartbeat was detected from the VMware Tools service This value is initialized to zero when the virtual machine powers on It stays at zero until the first heartbeat is detected after which the value is always greater than zero until the virtual machine is power cycled again For additional information see the next section DevicelsConnected devName Boolean GET Returns True if the specified device is connected Otherwise False is returned Productinfo infoType integer VmProduct or VmPlatform GET Returns an integer representing the value of the product information field specified by infoType which is of type VmProdInfoType See VmProdInfoType on page 34 for a list of valid types and return values Uptime Note This property does not apply to ESX Server 3 integer Accesses the uptime of the guest operating system on the virtual machine Note
87. emote console connections API connections and Web based management interface connections to the specified virtual machine vm gt get execution state Returns the defined va undef undefined va ue on success or ue on failure Returns the virtual machine s current state powered on powered off suspended or stuck For a list of the execution states see VM_EXECUTION_STATE_ lt XXX gt Values on page 70 vm gt get_guest_info Returns the defined va undef undefined va Skey name ue on success or ue on failure vm gt set guest info Skey name value Returns the defined va undef undefined va ue on success or ue on failure t accesses a shared variable identified by the string key_name f you write a Guestinfo variable by using the set guest info method the new value is written into memory and is discarded when the virtual machine process terminates For additional information see Using VmPerl to Pass User Defined nformation Between a Running Guest Operating System and a Script on page 73 Svm gt get config Returns the defined va undef undefined va ile name ue on success or ue on failure Returns a string containing the configuration file name for the virtual machine This method fails if the VMware VmPerl VM object is not connected www vmware com CHAPTER 4 Using VmPerl Method Description vm gt get_config
88. er because of a proxy failure You see this error only if you have configured your remote workstation to use a Web proxy For more information on using a Web proxy see your VMware product documentation vmErr TIMEOUT VM E TIMEOUT There is no response to the request the operation timed out vmErr_UNSPECIFIED VM_E_UNSPECIFIED An unspecified error has occurred vmErr VMBUSY VM E VMBUSY You attempted to connect to a virtual machine that is under the control ofa local console running on the server vmErr VMEXISTS VM E VMEXISTS You attempted to register a virtual machine that is already registered vmErr_VMINITFAILED VM_E_VMINITFAILED The virtual machine process could not be started on the server www vmware com CHAPTER 6 Error Codes and Event Logging Event Logging If you are running GSX Server on a Windows machine you can use Event Viewer to view the following types of events for virtual machines Power transitions By default Event Viewer logs an event whenever the virtual machine changes power state on off or suspended x essages essages occur whenever an error condition exists in a virtual machine The Event Viewer logs a message with its type hint warning error or question the text of the message and he choices to acknowledge a message x essage answers When a message is acknowledged the answer is logged with the message that is answe
89. er events Right click on a sing e event log and select Properties The Event Properties window is displayed 112 with additional details about the event as shown in the following image Event Date 5 9 2002 Source VMware GSX Server Time 1217 Category Virtual machines Type Information EventID 1100 User NA Computer BROOKLYN Description Virtual machine powered on was powered off d vm win2k windows 2000 professional vmx Data Bytes Words OK Cancel Apply www vmware com CHAPTER 6 Error Codes and Event Logging Reading the Event Log Each event always begins with a string that describes what happened to the virtual machine Power Transitions The Event Viewer logs virtual machine power transitions as Windows information type events EVENTLOG_INFORMATION_TYPE Each power transition event log begins with a simple string indicating the new power state of the virtual machine Power transition event log strings follow In these examples D foo vmx is the path to the configuration file for the virtual machine Virtual machine powered on was powered off D foo vmx Virtual machine powered off was powered on D foo vmx Virtual machine suspended was powered on D foo vmx Messages The Event Viewer logs messages with a severity appropriate for the message VMware hints have an info type and are logged as a Windows information type event EVENTLOG_INFOR
90. erver where Shostname is the server s hostname or IP address If Shostname is not given or undefined the authentication is performed on the local system The C library connects to the local host and uses current user information when it connects However this user information is not passed back to Sconnectparams Otherwise you may supply the user name and password for authentication as that user Gets or set the TCP port to use when connecting to the server Its default value is O zero indicating the default port number should be used Otherwise enter the correct port number A port number set to a negative value is treated as an incorrect value and the default port number is used instead Note The default port number for ESX Server 3 x is 443 the default port number for ESX Server 2 x and other VMware products is 902 If your script connects to ESX Server 3 x and to other products or versions as well we recommend that you supply a value of undef for the port number which allows the server port number to be selected automatically Sconnectparams gt get_username Returns the defined value on success or undef undefined value on failure or if the value is not set Set the value and retry the API call connectparams gt set username Susername Gets or set the name of a user on the server 56 www vmware com CHAPTER 4 Using VmPerl Method Description connectparams gt get_passwo
91. et guestinfo name Sending Information Set in the Guest Operating System to a VmPerl Script Similarly in a virtual machine s guest operating system you can use the VMware Tools service to set Guestinfo variables for the virtual machine Use the following to write the GuestInfo variable key_name In a Windows guest operating system VMwareService exe cmd info set guestinfo lt key name gt lt value gt www vmware com CHAPTER 4 Using VmPerl In a Linux guest operating system etc vmware tools vmware guestd cmd info set guestinfo lt key name gt lt value gt Continuing with the previous example Susan Williams prefers Sue To set the value of Sue Williams for the name variable type the following in a Linux guest operating system etc vmware tools vmware guestd cmd info set guestinfo name Sue Williams Retrieving Information in a VmPerl Script With the VmPerl API you use the vm gt get guest info method to retrieve information set in the guest operating system into a VmPerl script running on any machine including GSX Server or any remote workstation that can connect to the virtual machine For example to retrieve Sue s name set by the VMware Tools service query the guest operating system by using the VmPerl API Svm gt get_guest_info name 75 VMware Scripting API User s Manual www vmware com 76 CHAPTER Using Sample VmPerl Scripts This section contains sa
92. ethod sets a virtual device to the disconnected state where devName is a string that identifies the virtual device you want to disconnect The virtual machine must be powered on for this method to succeed otherwise a vmeErr_BADSTATE error is returned object SetRunAsUser lt myuseraccount gt Runs the virtual machine as the user specified by the lt mypassword gt lt myuseraccount gt and lt mypassword gt Note This method applies only to GSX Server 3 1 object RunAsUser Returns the name of the user running the virtual machine Note This method applies only to GSX Server 3 1 31 VMware Scripting API User s Manual 32 VmQuestion The VmQuest ion object is created and returned by VmCt1 PendingQuestion It describes a question or error condition requiring user input Once the script selects one of the possible answers it passes the object and the selected answer as inputs to VmCt1 AnswerQuestion The VmQuest ion object includes the read only GET properties listed in the following table Property Name Property Type Access Type Description Text string GET Gets the question text Choices string GET Gets a VnCollect ion of strings representing a list of possible answers to the question Id integer GET Gets an integer used internally by the VmCOM component to identify the question www vmware com CHAPTER 2 Using VmCOM Symbolic Constant Enumerations
93. f vm gt connect connect_params Scfg path my SerrorNumber SerrorString Svm gt get last error Destroys the virtual machine object thus disconnecting from the virtual machine undef vm die Cannot connect to vm Error SerrorNumber errorString n Gets the Power status of the virtual machine to determine if it is running my ScurState Svm gt get execution state if curState VM_EXECUTION STATE ON print Can only suspend a powered on Virtual Machine n else Suspends the running vm if vm gt suspend my SerrorNumber SerrorString Svm gt get last error print Couldn t suspend Error SerrorNumber SerrorString n Destroys the virtual machine object thus disconnecting from the virtual machine undef Swm 95 VMware Scripting API User s Manual 96 Setting a Virtual Machine s IP Address Configuration Variable This Perl script invokes the VMware guest operating system service to set a virtual machine s IP address ip configuration variable This sample script complements the following sample script that retrieves a virtual machine s IP address ip configuration variable The saveguestip pl script runs inside a virtual machine while the getguestip p sample script runs in the host operating system or another machine See Getting a Virtual Machine s IP Address on page 99 For more information on passing information between a script and a guest operating system se
94. fg path gt getcapabilities Note This method applies only to ESX Server 2 and earlier Returns the access permissions for the current user This number is a bit vector where 4 read 2 write and 1 execute For a user with all three permissions a value of 7 is returned when this property is used in a script vmware cmd lt vm cfg path gt getremoteconnections Note This method applies only to ESX Server 2 and earlier Returns the number of remotely connected users This value includes the number of remote consoles Scripting APIs and Web based management interface connections to the virtual machine vmware cmd lt vm cfg path gt setrunasuser lt username gt lt password gt Note This method applies only to GSX Server 3 1 Runs the virtual machine as the user specified by the lt username gt and lt password gt vmware cmd lt vm cfg path gt getrunasuser Note This method applies only to GSX Server 3 1 Returns the name of the user running the virtual machine www vmware com CHAPTER 7 vmware cmd Utility lt powerop_mode gt Values The following table describes hard soft and trysoft power operations Powerop_mode Values Description soft Start when a virtual machine is suspended After resuming the virtual machine the To succeed soft power operations operation attempts to run a script in the guest operating system The Start operation require the current version of
95. fg path gt setconfig lt variable gt lt value gt Sets a configuration variable for the virtual machine connected to the remote console The new value is written into memory and is discarded when the virtual machine process terminates You cannot change the value of a configuration variable in a virtual machine s configuration file Do not change the memory size while a virtual machine is suspended First power off the virtual machine then change its memory size vmware cmd lt vm cfg path gt getconfig lt variable gt Retrieves the value for a configuration variable for the virtual machine connected to the remote console vmware cmd lt vm cfg path gt setguestinfo lt variable gt lt value gt Writes a Guestinfo variable into memory The variable is discarded when the virtual machine process terminates vmware cmd lt vm cfg path gt getguestinfo lt variable gt Retrieves the value for a Guestinfo variable www vmware com CHAPTER 7 vmware cmd Utility Virtual Machine Operation Description vmware cmd lt vm cfg path gt getproductinfo lt prodinfo gt Returns information about the product where lt prodinfo gt is product platform build majorversion product s major version number minorversion product s minor version number or revision If product is specified the return value is one of the following ws VMware Workstation gsx VMware GSX Server esx VMware ESX Server
96. for VmPerl scripts see Using Sample VmPerl Scripts on page 77 For the list of error codes see Error Codes on page 108 Note For more information about VMware API development see www vmware com support developer 13 VMware Scripting API User s Manual Installing the VMware Scripting API GSX Server You have the option of installing the VMware Scripting API on your GSX Server when you installed the software However if you want to run VMware Scripting APIs on a remote workstation you need to install VmCOM or VmPerl on that machine Your administrator will provide you with the appropriate script or executable file or ask you to download it from the VMware Management Interface requires customization ESX Server To download the VMware Scripting API packages go to the Download page www vmware com download of the VMware Web site Click Download next to the appropriate ESX Server version Enter your email address and password then accept the end user license agreement to get to the packages Click on the appropriate API package link The links are COM API EXE COM Scripting API for Windows operating systems Use this package on a Windows client machine Perl API EXE Perl Scripting API for Windows operating systems Use this package on a Windows client machine Perl API Compressed Tar Archive Perl Scripting API for Linux operating systems Use this package on a Linux client machine To install the Pe
97. gher This is not and min minimum memory size for all virtual machines supported in ESX Server 3 system mem shared NT Memory allocated to running virtual machines that is securely shared with other virtual machines system mem sharedCommon T Total amount of memory in MB that s required for a single copy of Note This applies only to ESX shared pages in running virtual machines Server 2 1 1 and higher system mem sharedVM ji Total amount of shared memory in MB for running virtual machines Note This applies only to ESX This is the same value as the sum of system mem shared and Server 2 1 1 and higher system mem sharedCommon system mem size T Sum of the current memory size in KB for all running virtual machines system mem sizetgt T Sum of the target memory size in KB for all running virtual machines system mem swapin T Cumulative memory in KB swapped into memory since the last Note This applies only to ESX Server 2 1 1 and higher This is not supported in ESX Server 3 time ESX Server was booted 131 VMware Scripting API User s Manual Variable Name Variable Type Description system mem swapout Note This app Server 2 1 1 and lies only to ESX higher This is not supported in ESX Server 3 INT Cumulative memory in KB swapped out to disk since the last time ESX Server was booted system mem swapped Sum of currently swapped memory in KB for all running v
98. he internal state of the virtual machine is included in the snapshot If lt memory gt is 0 then the power state of the snapshot is set to powered off If a snapshot already exists the method updates the existing snapshot The method fails if a snapshot is already in progress 63 VMware Scripting API User s Manual 64 Method Description vm gt revert to snaps Note This method ap Server 3 hot plies only to ESX Reverts the virtual machine to the current snapshot If no snapshot exists then this method does nothing and the virtual machine state remains unchanged If a snapshot was taken while a virtual machine was powered on and this method is invoked after the virtual machine was powered off the method causes the virtual machine to power on to reach the snapshot state vm gt remove snapshot Note This method ap Server 3 plies only to ESX Removes the current snapshot belonging to the virtual machine If no snapshot exists then this method does nothing vm gt has_snapshot Note This method ap Server 3 plies only to ESX Returns 1 if the virtual machine already has a snapshot If no snapshot exists then this method returns 0 vm gt get connected Returns the defined va users ue on success or an empty list undef undefined value on failure Returns a list of local and remote connected users and their IP addresses This list includes r
99. if there is a failure You can use Svm gt get last errorto determine if an error occurred or if the device is not connected Replies to a question where quest ion represents the question and choice represents the index of the selected answer to the question The index is a number associated with an answer The first choice s index is always 0 The second choice s index is 1 and so on Use this method to answer the current question or dismiss the current error message when a virtual machine is in the VM EXECUTION STATE STUCK state and requires user input to continue First get a VMware VmpPerl Question object from the VMware VmPerl VM objects get pending question method You can retrieve the possible choices and their respective indices from the VMware VmPerl Question objects get choices method Then use the answer_question method to answer the question Determines the connection state where dev_name identifies the virtual device Svm gt connect device dev name Returns the defined value on success or undef undefined value on failure Sets a virtual device to the connected state where dev_name identifies the virtual device you want to connect The virtual machine must be powered on for this method to succeed otherwise a VM E BADSTATE error is returned Use the set config method to set configuration parameters relevant to the virtual device before calling the connect device method The following co
100. igured for autostart amp config end if Err Clear else if auto start true or auto start TRUE then Check that the VM is powered off power state vm ExecutionState if Err Number lt gt 0 then WScript Echo Error getting execution state amp Err Number amp amp Err Description Err Clear else if power state vmExecutionState Off or power state vmExecutionState Suspended then WScript Echo Powering on amp config vm Start vmPowerOpMode_Soft if Err Number lt gt 0 then WScript Echo Error powering on amp config amp amp Err Description Err Clear else Wait between starting up VMs to smooth out the load on the server WScript Sleep 5000 end if end if end if end if end if end if next www vmware com 50 CHAPTER 3 Using Sample VmCOM Programs The source for the sample program 3 accompanying Windows Script File is in the SampleScripts folder in the VmCOM Scripting API directory You can also find it on the VMware Web site saved with a TXT extension for online viewing at www vmware com support developer scripting APl doc sample3 wsf txt Note If you are using Microsoft Internet Explorer as your browser select View gt Source to view the file Alternately right click this link and download this file lt job id sample3 gt lt reference object VmCOM Vmctl gt lt script language VBScript src sample3 vbs gt lt job gt 51 VMware Scripting AP
101. ile to launch the same nonpersistent virtual disk multiple times in a training or testing environment where each virtual machine would be unique on the network Note that in the case of persistent or undoable disks each virtual disk file must be copied into its own directory if it shares its file name with another virtual disk file When a virtual machine process is created on the server all GuestInfo variables are initially undefined A Guestinfo variable is created the first time it is written You identify a GuestInfo variable with a key name You can define and create any number of GuestInfo variable key names The information you pass is temporary lasting until the virtual machine is powered off and all consoles connected to the virtual machine are closed For an example showing how the VMware guest service can be invoked in a Perl script see the sample Perl script to get the IP address of a guest operating system on Setting a Virtual Machine s IP Address Configuration Variable on page 96 73 VMware Scripting API User s Manual 74 Sending Information Set in a VmPerl Script to the Guest Operating System To send information from a VmPerl script to a running guest operating system you use VmPerl API s vm gt set guest info method You need to specify a variable name Skey name and its value value For example you might want to deploy virtual machines for a training class When a virtual machine starts you
102. ion The Scripting API does not support using symbolic links to refer to virtual machine configuration paths on remote hosts with ESX Server 3 installed Scripts that try to open virtual machines using symbolic links will fail with an error unless they are run in the Service Console of the virtual machine s host system When using the Scripting API remotely with ESX Server 3 identify virtual machines with their absolute UUID based path or their datastore path For example a path that uses a UUID might look like this vmts volumes 19496567 9ac80b57 testVM vm1 vmx Alternatively the same virtual machine can be opened using a datastore path that might look like this mystorage test VM vm1 vmx Both of these configuration file path formats can be used anywhere a configuration path is required UUID and datastore formats can be used interchangeably For more information on path format specifications refer to the VMware Infrastructure SDK Programming Guide www vmware com CHAPTER 4 Using VmPerl Snapshots and Redo Logs ESX Server 3 introduces the concept of snapshots to the Scripting API Prior to ESX Server 3 it was possible to roll back virtual machine disk state to a designated point by using redo logs on a per disk basis With ESX Server 3 virtual machine state can be captured as a whole in a snapshot which optionally includes the memory state of a running virtual machine The snapshot feature is implemented with several ne
103. ion swap file for a virtual machine This value should approach mem swaptgt next row in this table mem swaptgt NT Target memory size in KB to swap to the VMFS swap file for a virtual machine 137 VMware Scripting API User s Manual Server 3 Variable Name Variable Type Description mem affinity string Specifies memory affinity for a virtual machine to a single Note This is not supported in ESX Read write NUMA node Server 3 mem max NT Size of the maximum memory for a virtual machine This is the Read write amount of memory a virtual machine thinks it has In ESX Server 2 0 mem max is in KB In ESX Server 2 0 1 and higher mem max is in MB mem min NT Size of the minimum memory for a virtual machine Read write In ESX Server 2 0 mem min is in KB In ESX Server 2 0 1 and higher mem min is in MB mem shares NT Number of memory shares assigned to a virtual machine Read write You can use memory shares to calculate proportional server resource allocation between virtual machines Disk Statistics disk HTL string Space delimited set of disks specified as a set of host target LUN HTL for example vmhba0 0 0 or vmhbal1 0 1 disk lt HTL gt KBread T Total data read in KB for the virtual machine on the target device specified by lt HTL gt disk lt HTL gt KBwritten T Total data written in KB for the vir
104. irtual machines It is the same value as when system mem swapin is subtracted from system mem swapout system mem swaptgt Note Server 3 This is not supported in ESX For all running virtual machines the target memory size in KB used for swapping to the VMFS swap files system mem sysCodeSize Note This app Server 2 1 1 and suppor lies only to ESX higher This is not ed in ESX Server 3 VMkernel code size memory used to store the executable instructions of the VMkernel system mem sysHeapSize Note This app Server 2 1 1 and ies only to ESX higher Amount of memory allocated in KB to the VMkernel heap file system mem sysUsage Note This app Server 2 1 1 and suppor ies only to ESX higher This is not ed in ESX Server 3 Amount of overhead memory in KB currently used by the VMkernel system mem to Note This app Server 2 1 1 and supported in alMem ies only to ESX higher This is not ESX Server 3 Total amount of memory in KB on ESX Server system mem to Note This app Server 2 1 1 and supported in ESX Server 3 alSwap ies only to ESX higher This is not system Note TI Server 3 mem vmkUsage is is not suppor ed in ESX Total amount of swap space in MB on ESX Server Amount of memory in KB currently used by the VMkernel system Note TI Server 3 mem vmkernel is is not suppor ed
105. irtual machines 1100 information 5 9 2002 12 16 13 PM VMware GSX Server Virtual machines 1100 information 5 9 2002 12 16 09 PM VMware GSX Server Virtual machines 1100 Dinformation 5 9 2002 12 16 07 PM VMware GSX Server Virtual machines 1102 information 5 9 2002 12 16 05PM VMware GSX Server Virtual machines 1101 information 579 2002 12 15 57 PM VMware GSX Server Virtual machines 1100 GD Information 5 9 2002 12 15 51 PM VMware GSX Server Virtual machines 1100 information 5 9 2002 12 15 51 PM VMware GSX Server Virtual machines 1102 A warning 5 9 2002 12 15 50PM VMware GSX Server Virtual machines 1101 information 5 9 2002 12 15 50PM YMware GSX Server Virtual machines 1102 A waring 5 9 2002 12 15 49PM_VMware GSX Server Virtual machines 1101 Ci Information statznn 17 15 48 PM VMware GSX Server Virtual machines 1102 fi You can use the filtering feature in Event Viewer to see selected events on a virtual machine All virtual machine events are stored in the Virtual Machines category By contrast all serverd and authd events are stored in the default None category Each event type has an event ID For example all virtual machine power transition events share the event ID 1100 You may use this event ID to filter virtual machine events The event IDs for virtual machines are listed i n the following table Event ID Event Type 1100 Power transition events 1101 Message events 1102 Message answ
106. is manual Instead we include the first line of the copyright followed by ellipses to indicate its placement The complete copyright is as follows Copyright c 1998 2004 VMware Inc Permission is hereby granted free of charge to any person obtaining a copy of the software in this file the Software to deal in the Software without restriction including without limitation the rights to use copy modify merge publish distribute sublicense and or sell copies of the Software and to permit persons to whom the Software is furnished to do so subject to the following conditions The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software The names VMware and VMware Inc must not be used to endorse or promote products derived from the Software without the prior written permission of VMware Inc Products derived from the Software may not be called VMware nor may VMware appear in their name without the prior written permission of VMware Inc THE SOFTWARE IS PROVIDED AS IS WITHOUT WARRANTY OF ANY KIND EXPRESS OR IMPLIED INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT IN NO EVENT SHALL VMWARE INC BE LIABLE FOR ANY CLAIM DAMAGES OR OTHER LIABILITY WHETHER IN AN ACTION OF CONTRACT TORT OR OTHERWISE ARISING FROM OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALING
107. ist of ESX Server system variables see VMware ESX Server System Resource Variables on page 130 vmware cmd s setresource lt variable_name gt lt value gt Note These methods apply only to ESX Server Sets the value of the ESX Server system resource variable specified by system lt variable_name gt For a list of ESX Server system variables see VMware ESX Server System Resource Variables on page 130 117 VMware Scripting API User s Manual 118 vmware cmd Operations on a Virtual Machine The syntax for this utility on a virtual machine is vmware cmd lt options gt lt vm cfg path gt lt vm operation gt lt arguments gt The vmware cmd utility performs the following operations on a virtual machine where lt vm cfg path gt represents the complete path to the virtual machine s configuration file Using Symbolic Links Many vmware cmd operations require you to supply a path to a virtual machine used in the operation The vmware cmd utility does not support using symbolic links to refer to virtual machine configuration paths on remote hosts with ESX Server 3 installed If you try to use symlinks to refer to virtual machines on an ESX Server 3 host vmware cmd will fail with an error unless you are runnng vmware cmd in the Service Console of the virtual machine s host system When using the vmware cmd with ESX Server 3 identify virtual machines with their absolute UUID based path or their datastor
108. ithin the specified Interval then this script will forcefully shutdown ConfigToCheck and start ConfigToStart usage You can use this script to check the virtual machine specified by hbcheck pl lt ConfigToCheck gt lt ConfigToStart gt Interval BEGIN if 0 eq MSWin32 INC Set the path to your VmPerl Scripting directory if different C Program Files VMware VMware VmPerl Scripting API perl5 site perl 5 005 C Program Files VMware VMware VmPerl Scripting API per15 site_perl1 5 005 MSWin32 x86 Import required VMware Perl modules and version use VMware VmPerl use VMware VmPerl VM use VMware VmPerl ConnectParams use strict Display the script usage sub usage print STDERR Usage hbcheck pl lt config_to_check gt lt config to start gt interval in secs n exit 1 87 VMware Scripting API User s Manual 88 Retrieves a pre defined constant value sub vm_constant my Sconstant_str shift return VMware VmPerl constant constant str 0 Read in command line options usage unless scalar ARGV 3 scalar ARGV 2 my cfg_to_check shift my Scfg to start shift my Sinterval shift Set the interval to 30 seconds if it is not specified Sinterval 30 Connect to the local host on the default port as the current user my connect params VMware VmPerl ConnectParams new undef undef
109. itten You identify a Guestinfo variable with a key name You can define and create any number of GuestInfo variable key names The information you pass is temporary lasting until the virtual machine is powered off and all consoles connected to the virtual machine are closed www vmware com CHAPTER 2 Using VmCOM Sending Information Set ina VmCOM Script to the Guest Operating System To send information from a VmCOM script to a running guest operating system you use the Guest Info property You need to specify the string value of the configuration variable identified by keyName For example you might want to deploy virtual machines for a training class When a virtual machine starts you want to display a banner welcoming the student to the class You can pass their name from a YmCOM script to the guest operating system on a student s virtual machine If you have not already done so connect a VmCt1 object and set the student s name for this virtual machine to Susan Williams vm GuestInfo name Susan Williams This statement passes a string name to the guest operating system A script in the guest operating system reads the string then calls a command specific to the guest operating system to set the student s name in the banner This operation is explained in the following section This setting lasts until you power off the virtual machine and close all connected consoles Retrieving the Information i
110. key_name Returns the defined value on success or undef undefined value on failure vm gt set_config key_name value Returns the defined value on success or undef undefined value on failure Accesses the value of a configuration variable identified by the string key_name When a virtual machine process is spawned on the server the process reads configuration variables from the virtual machine s configuration file into memory If you write a configuration variable by using the set config method the new value is written into memory and is discarded when the virtual machine process terminates You cannot change the value of a configuration variable in a virtual machine s configuration file The method throws an error if it accesses an undefined configuration variable Do not change the memory size while a virtual machine is suspended First power off the virtual machine then change its memory size Svm gt get product info Sinfotype Returns the defined value on success or undef undefined value on failure Gets information about the product For additional information see Infotype Values on page 71 vm gt get_heartbeat Returns the defined value on success or undef undefined value on failure Returns the current heartbeat count generated by the VMware Tools service running in the guest operating system The count is initialized to zero when the virtual machine is powered on The heartbeat coun
111. le systems in the virtual machine This assures that a disk snapshot represents a consistent state of the guest file systems lt memory gt can be 0 or 1 If lt memory gt is 1 then a dump of the internal state of the virtual machine is included in the snapshot If lt memory gt is 0 then the power state of the snapshot is set to powered off If a snapshot already exists the method updates the existing snapshot The method fails if a snapshot is already in progress object RevertToSnapshot Note This method applies only to ESX Server 3 Reverts the virtual machine to the current snapshot If no snapshot exists then this method does nothing and the virtual machine state remains unchanged If a snapshot was taken while a virtual machine was powered on and this method is invoked after the virtual machine was powered off the method causes the virtual machine to power on to reach the snapshot state object RemoveSnapshot Note This method applies only to ESX Server 3 object HasSnapshot Note This method applies only to ESX Server 3 Removes the current snapshot belonging to the virtual machine If no snapshot exists then this method does nothing Returns 1 if the virtual machine already has a snapshot If no snapshot exists then this method returns 0 object AnswerQuestion lt question gt lt choice gt The AnswerQuestion method replies to a question where question is a VmQuestion obj
112. line saving you the effort of connecting to the virtual machine from a console or the VMware Management Interface in order to answer the question This script answer_question p1 saved with a TXT extension for online viewing can be found on the VMware Web site at www vmware com support developer scripting APl doc answerquestion pl txt usr bin perl w Copyright C 1998 2004 VMware Inc answerquestion pl You can use this script to check if the virtual machine specified by config is stuck If it s stuck you can answer any question posed by this virtual machine to allow it to continue usage answerquestion pl lt config file gt BEGIN if O eq MSWin32 INC Set the path to your VmPerl Scripting directory if different C Program Files VMware VMware VmPerl Scripting API perl5 site perl 5 005 C Program Files VMware VMware VmPerl Scripting API per15 site_perl 5 005 MSWin32 x86 Import the required VMware Perl modules and version use VMware VmPerl use VMware VmPerl VM use VMware VmPerl ConnectParams use VMware VmPerl Question use strict www vmware com CHAPTER 5 Using Sample VmPerl Scripts Read in command line options my cfg shift or die Usage 0 lt config file gt n Connect to the local host on the default port as yourself my connect params VMware VmPerl ConnectParams new Initialize the object for th
113. m CHAPTER 5 Using Sample VmPerl Scripts my connect params VMware VmPerl ConnectParams new server name Sport user passwd To connect to a local server you would use the following line my S connect_params VMware VmPerl ConnectParams new undef port user passwd He To connect to a local server as the current user you would use the following line my connect params VMware VmPerl ConnectParams new Establish a persistent connection with server my server VMware VmPerl Server new if server gt connect Sconnect params my Serror number Serror string Sserver gt get last error die Could not connect to server Error Serror number Serror stringin print nThe following virtual machines are registered n Obtain a list containing every config file path registered with the server my elist server gt registered_vm_names if defined list 0 my Serror number Serror string Sserver gt get last error die Could not get list of VMs from server Error Serror number Serror string n print An foreach list Destroys the server object thus disconnecting from the server undef Sserver 81 VMware Scripting API User s Manual 82 Starting All Virtual Machines on a Server You can use a script like the following to start all virtual machines that are not already running on a server This script powers on
114. machine specified by vm to start Use the TRYSOFT mode to shutdown gracefully if possible Svm gt stop vm constant VM PONEROP MODE TRYSOFT undef vm Initialize the new virtual machine object my vm_to_start VMware VmPerl VM new if vm_to_start gt connect S connect params cfg_to_start my Serror_ number Serror string vm to start gt get last error die Could not connect to virtual machine at Scfg to startan Error Serror number error_string n Start the new virtual machine and clean up my start ok Svm to start gt start unless Sstart ok my Serror number Serror string vm to start gt get last error undef Svm to start die Could not start virtual machine Scfg to start n Error Serror number error_string n undef vm_to_start die Lost heartbeat of cfg_to_check npowered on cfg_to_start n else Wait Sinterval seconds before checking for the virtual machine s heartbeat print Got heartbeat count hb n sleep Sinterval Slast hb Shb 89 VMware Scripting API User s Manual 90 Answering Questions Posed by a Virtual Machine You can use a script like the following to answer a question posed by a virtual machine in a stuck state that is one that is waiting for user acknowledgment before it can complete an operation such as suspending or resuming the virtual machine The script allows the question to be answered at the command
115. mple Perl scripts written by VMware to demonstrate example uses of the VmPerl API You can modify these scripts to suit the needs of your organization These scripts are located in the SampleScripts subdirectory in the VmPerl directory or on the VMware Web site Note The scripts on the Web site are saved with a TXT extension for online viewing Remove the TXT extension before using these scripts The sample scripts illustrate Listing the Virtual Machines on the Server Starting All Virtual Machines on a Server Checking a Virtual Machine s Power Status Monitoring a Virtual Machine s Heartbeat Answering Questions Posed by a Virtual Machine Suspending a Virtual Machine Setting a Virtual Machine s IP Address Configuration Variable Getting a Virtual Machine s IP Address 77 VMware Scripting API User s Manual Adding a Redo Log to a Virtual Disk ESX Server 2 x only Committing a Redo Log to a Virtual Disk without Freezing the Virtual Machine ESX Server 2 x only Note If you plan on using the VMware Perl API remotely on a Windows machine you must copy your scripts into the same directory in which you installed the VMware Perl API www vmware com 78 CHAPTER 5 Using Sample VmPerl Scripts Copyright Information Each sample script and sample program included with the VmPerl Scripting API includes a copyright However for brevity we do not include this copyright in its entirety with each sample script and sample program in th
116. n name v vme nt4smpscsighosted nt smpscsighosted vma Power a ower off Shutdowr Poe Variable name Variable value Configuration Guestinfo Read Write Heartbeat Tools last active Product info Version Product Platform Build Device name Connect device Disconnect device __Get connection state Selected virtual machine requires input to this question ot message fA redo log for undoable disk nt4SmpSesiGhosted vmdk was found Commit Discard Append Cancel 41 VMware Scripting API User s Manual 42 JScript and VBScript Sample Programs The sample scripts included in the SampleScripts folder are designed to run under the Windows Script Host environment which is included with all Microsoft Windows 2000 and subsequent compatible operating systems To run a script under a different environment such as an ASP or HTML page refer to that environment s documentation Each sample program comprises two files a script witha js UScript or vbs VBScript extension and the accompanying Windows Script File with the same name and the wsf extension For example the first sample program consists of the files sample1 js and sample1 wsf Both the script and the associated ws file must be in the same directory when you execute the sample program To execute a sample program type the following in a command line window escript nologo sample lt n gt wsf where lt n gt is the sample p
117. n page 72 VM PRODINFO BUILD The product s build number VM PRODINFO VERSION MAJOR The product s major version number 71 VMware Scripting API User s Manual Infotype Values Description VM_PRODINFO_VERSION_MINOR The product s minor version number VM_PRODINFO_VERSION_REVISION The product s revision number VM PRODINFO PRODUCT lt XXX gt Values The get product info method returns the VMware product when the requested SinfotypeisVM PRODINFO PRODUCT lt XXX gt VM PRODINFO PRODUCT Values Description VM PRODUCT WS The product is VMware Workstation VM PRODUCT GSX The product is VMware GSX Server VM PRODUCT ESX The product is VMware ESX Server VM PRODUCT UNKNOWN The product is unknown VM PRODINFO PLATFORM lt XXX gt Values The get product info method returns the host s platform when the requested SinfotypeisVM PRODINFO PLATFORM lt XXX gt VM PRODINFO PLATFORM Values Description VM PLATFORM WINDOWS The platform is a Microsoft Windows operating system VM PLATORM LINUX The platform is a Linux operating system VM PLATFORM VMNIX The platform is the VMware Service Console VM PLATFORM UNKNOWN The platform is unknown www vmware com 72 CHAPTER 4 Using VmPerl Using VmPerl to Pass User Defined Information Between a Running Guest Operating System and a Script When the guest operating system is running in
118. n the Guest Operating System nthe running guest operating system you use the VMware Tools service to retrieve variables set for the virtual machine You can then use this passed name string inside a guest operating system startup sequence Use the following to read the Guestinfo variable keyName n a Windows guest operating system VMwareService exe cmd info get guestinfo lt keyName gt na Linux guest operating system etc vmware tools vmware guestd cmd info get guestinfo lt keyName gt For example to get the current value for the name variable you can type the following in a Linux guest operating system etc vmware tools vmware guestd cmd info get guestinfo name Sending Information Set in the Guest Operating System to a VmCOM Script Similarly in a virtual machine s guest operating system you can use the VMware Tools service to set Guestinfo variables for the virtual machine Use the following to write the Guestinfo variable keyName In a Windows guest operating system VMwareService exe cmd info set guestinfo lt keyName gt lt value gt 37 VMware Scripting API User s Manual 38 In a Linux guest operating system etc vmware tools vmware guestd cmd info set guestinfo lt keyName gt lt value gt Continuing with the previous example Susan Williams prefers Sue To set the value of Sue Williams for the name variable type the following in a Linux guest operating
119. name Sport user passwd Create a Server object my S server VMware VmPerl Server new Establish a persistent connection with server if server gt connect connect_params my Serror number Serror string Sserver gt get last error die Could not connect to server Error Serror number Serror_string n Get a list of all virtual machine configuration files registered with the server my elist server gt registered_vm_names if defined list 0 my Serror number Serror string Sserver gt get last error die Could not get list of VMs Error Serror number Serror stringin my S config foreach config list my vm VMware VmPerl VM new Connect to the VM using the same ConnectParams object if vm gt comect connect params config my Serror number Serror string server gt get_last_error print STDERR Could not connect to VM Sconfig Error Serror number Serror string n else Only power on VMs with the config setting autostart true my Sautostart vm gt get_config autostart if Sautostart amp amp Sautostart true i Only try this for VMs that are powered off or suspended my Spower state Svm gt get execution state if defined Spower state my Serror number Serror string Sserver gt get last error print STDERR Could not get execution state of VM config Error 83 VMware Scripting API
120. nbe Oor1 lf freezeis 0 then the virtual machine is not frozen when changes are committed though it runs more slowly If freeze is 1 then the virtual machine is frozen until the commit operation finishes If level is 0 then the virtual machine must be frozen when changes are committed and freeze is ignored Swait canbe 0 or1 If Swait is 0 then the method returns as soon as the commit begins If wait is 1 then the method does not return until the commit completes The method fails if the specified virtual disk does not exist the specified virtual disk is in nonpersistent mode an online commit is already in progress or the virtual disk currently has no redo logs vm gt create_snapshot lt name gt lt description gt lt quiesce gt lt memory gt Note This method applies only to ESX Server 3 This method creates a snapshot of the virtual machine lt name gt is a user defined string value used as a non unique identifier for the snapshot lt description gt is a string describing the snapshot lt quiesce gt can be 0 or 1 If lt quiesce gt is 0 then the snapshot is taken immediately If lt quiesce gt is 1 and the virtual machine is powered on when the snapshot is taken VMware Tools is used to quiesce the file systems in the virtual machine This assures that a disk snapshot represents a consistent state of the guest file systems lt memory gt can be 0 or 1 If lt memory gt is 1 then a dump of t
121. nd Spasswd are missing connect to localhost as current user my connect params VMware VmPerl ConnectParams new server name Sport user Spasswd my Svm VMware VmPerl VM new if vm gt connect Sconnect_params Scfg path my Serror number Serror string Svm gt get last error undef vm die Could not connect to vm Error Serror number error_string n Get the IP address of the virtual machine my Sip vm gt get guest info ip if defined Sip my Serror_number Serror string Svm gt get last error undef vm die Could not get IP address Error error number Serror_string n if ip undef vm die The guest OS did not set the variable ip An print The IP address of cfg_ path is n ip n Destroys the virtual machine object thus disconnecting from the virtual machine undef vm www vmware com CHAPTER 5 Using Sample VmPerl Scripts Adding a Redo Log to a Virtual Disk ESX Server 2 x only You can add a redo log to a virtual SCSI disk in a running virtual machine on ESX Server 2 x You can specify the disk on the command line or let the script give you a choice of disks to select that are associated with the virtual machine For example you can write a script to back up a virtual disk Add a new redo log then back up the virtual disk The virtual disk is no longer changing as all data is now written to the redo log For more information about the
122. nstant enumeration 33 VMware Scripting API User s Manual 34 VmPowerOpMode Values Description vmPowerOpMode_Soft To succeed soft power transitions require the current version of the Vmware Tools service to be installed and running in the guest operating system Start when a virtual machine is suspended After resuming the virtual machine it attempts to run a script in the guest operating system to restore network connections by renewing the DHCP lease The Start operation always succeeds However if the VMware Tools service is not present or is malfunctioning the running of the script may fail Start when virtual machine is powered off After powering on the virtual machine the operation attempts to run a script in the guest operating system when the VMware Tools service becomes active This default script does nothing during this operation as there is no DHCP lease to renew The Start operation always succeeds However if the VMware Tools service is not present or is malfunctioning the running of the script may fail Stop Attempts to shut down the guest operating system and then powers off the virtual machine Reset Attempts to shut down the guest operating system then reboots the virtual machine Suspend Attempts to run a script in the guest operating system that safely disables network connections such as releasing a DHCP lease before suspending the virtual machine
123. object to Nothing in Visual Basic object Start lt mode gt The Start method powers on a previously powered off virtual machine or resumes a suspended virtual machine where mode is a VmPowerOpMode object that specifies the Start operation s behavior For more information see VmPowerOpMode on page 33 If the virtual machine is powered off then it is powered on If it is suspended this method resumes the virtual machine If the virtual machine is in any other state the Start method fails and throws an error object Stop lt mode gt The Stop method shuts down and powers off a virtual machine where mode is a VmPowerOpMode object that specifies the Stop operation s behavior For more information see VmPowerOpMode on page 33 This method always fails if the virtual machine is not in the vmExecutionState On state This method 27 VMware Scripting API User s Manual 28 Method Description object Reset lt mode gt The Reset method shuts down then reboots a virtual machine where mode is a VnPowerOpMode object that specifies the operation s behavior For more information see VmPowerOpMode on page 33 This method always fails if the virtual machine is not in the vmExecutionState_Onstate object Suspend lt mode gt The Suspend method suspends a virtual machine where mode is a VmPowerOpMode object that specifies the Suspend operation s behavior It saves the current s
124. on on ToolsLastActive is heavily loaded this value may occasionally reach several seconds If he service stops running either because the guest operating system has experienced a failure or is shutting down the ToolsLastAct ive value keeps increasing You can use a script with the ToolsLastActive property to monitor the start of the VMware Tools service and once started the health of the guest operating system If the guest operating system has failed the ToolsLastAct ive property indicates how long the guest has been down The following table summarizes how you may interpret the ToolsLastActive property values ToolsLastActive Property Value Description 0 The VMware Tools service has not started since the power on of the virtual machine 1 The VMware Tools service is running and is healthy 2 3 4 0r5 The VMware Tools service could be running but the guest operating system may be heavily loaded or is experiencing temporary problems Greater than 5 The VMware Tools service stopped running possibly because the guest operating system experienced a fatal failure is restarting or is shutting down Methods The VmCt 1 object includes the methods listed in the following table You can connect to a virtual machine start stop suspend and resume virtual machines query and modify the configuration file settings and connect and disconnect devices www vmware com CHAPTER 2 Using VmCOM Excep
125. onfiguration file path formats can be used anywhere a configuration path is required UUID and datastore formats can be used interchangeably For more information on path format specifications refer to the VMware Infrastructure SDK Programming Guide Snapshots and Redo Logs ESX Server 3 introduces the concept of snapshots to the Scripting API Prior to ESX Server 3 it was possible to roll back virtual machine disk state to a designated point by using redo logs on a per disk basis With ESX Server 3 virtual machine state can be captured as a whole in a snapshot which optionally includes the memory state of a running virtual machine www vmware com Disk Device Names CHAPTER 2 Using VmCOM For certain operations you need to specify a virtual disk Virtual disks are specified from the perspective of the virtual machine us number The disk device name is a stri ing the virtual controller number and the virtual SCSI device ng in the format scsi lt m gt lt n gt where lt m gt is the virtual controller number and lt n gt is the virtual SCSI device number Each virtual disk has a unique combin ation of virtual controller number and virtual device number that compose the disk device name If you know the name of the virtual disk file you can locate the corresponding numbers in the vi tual machine s configuration file To determine the numbers in the disk device name view the contents of the virtual machine
126. ontrol connections through the API Note You can set a configuration variable as many times as you want through the API per virtual machine session but only the latest change is kept in the virtual machine session All of the variables in the following table can be queried by using the vm gt get resource method Some of these variables can also be modified with the vm gt set resource method These variables that can be both queried and modified are indicated where appropriate in the table Following the table we include some tips on using these resource variables efficiently See Using ESX Server Virtual Machine Resource Variables Efficiently on page 140 Note The following table includes a brief description for each of the resource variables For additional information refer to the man pages for cpu 8 hyperthreading 8 mem 8 and diskbw 8 Variable Name Variable Type Description CPU Statistics cpu number INT Number of CPUs configured for the virtual machine cpu emin INT Effective min minimum percentage of a CPU that is assigned to the virtual machine on CPU x cpu emin is always greater than cpu min This emin value can change when the virtual machine powers on or off and when any changes are made to CPU allocations for any running virtual machines 135 VMware Scripting API User s Manual Variable Name Variable Type Description cpu extrasec FLOAT Amo
127. ools is used to quiesce the file systems in the virtual machine This assures that a disk snapshot represents a consistent state of the guest file systems lt memory gt can be 0 or 1 If lt memory gt is 1 then a dump of the internal state of the virtual machine is included in the snapshot If lt memory gt is 0 hen the power state of the snapshot is set to powered off f a snapshot already exists the operation updates the existing snapshot The operation fails if a snapshot is already in progress vmware cmd lt vm cfg path gt reverttosnapshot Note This operation applies only to ESX Server 3 Reverts the virtual machine to the current snapshot If no snapshot exists hen this operation does nothing and the virtual machine state remains unchanged f a snapshot was taken while a virtual machine was powered on and this operation is invoked after the virtual machine was powered off the operation causes the virtual machine to power on to reach the snapshot state vmware cmd lt vm cfg path gt removesnapshot Note This operation applies only to ESX Server 3 Removes the current snapshot belonging to the virtual machine If no snapshot exists then this operation does nothing vmware cmd lt vm cfg path gt hassnapshot Note This operation applies only to ESX Server 3 Returns 1 if the virtual machine already has a snapshot If no snapshot exists then this operation returns 0 vmware cmd lt vm c
128. or code in your scripts use my ret Svm gt get last error www vmware com Common VmCOM and VmPerl Errors The following table is a partial list of common VmCOM and VmPerl errors Any error code not listed in this table indicates an internal failure in VmCOM VmPe VmCOM Error Code VmPerl Error Code CHAPTER 6 Error Codes and Event Logging or another VMware component Description vmErr BADSTATE VM E BADSTATE You attempted to move a virtual machine from a valid state to an invalid one For example you tried to restore a non suspended virtual machine or power on an already powered on virtual machine Either change the virtual machine s state for example from powered on to suspended or attempt a different operation vmErr BADVERSION VM E BADVERSION The version of the VmCOM component VmPerl module and the VMware server product are incompatible vmErr DISCONNECT VM E DISCONNECT The network connection to the virtual machine was lost vmErr INSUFFICIENT RESOURCES VM E INSUFFICIENT RESOURCES The operation failed because an internal or system limit was exceeded For example the Connect method may return this error ifthe maximum number of connected objects has been reached vmErr INVALIDARGS VM E INVALIDARGS The specified arguments are not valid for this operation vmErr INVALIDVM VM E INVALIDVM The virtual machine configuration file is invalid
129. pi distrib 5 Run the install script vmware install pl VMware Scripting API User s Manual 6 Press Enter to read the end user license agreement EULA You may page through it by pressing the space bar Ifthe Do you accept prompt doesn t appear press Q to get to the next prompt 7 Choose the directory to install the VmPerl executable files or accept the default location This directory includes the uninstall script for the VmPerl API 8 Choose the directory to install the VmPerl library files or accept the default location This directory includes the sample scripts for the YmPerl API The SampleScripts directory contains example scripts that demonstrate use of the VmPerl API You may customize these scripts for your particular organization See Using Sample VmPerl Scripts on page 77 for more information on the sample scripts This completes the VmPerl API installation At any time you can decide to remove this software from your system by invoking the following command as root lt executable files directory gt vmware uninstall api pl www vmware com 16 Using VmCOM CHAPTER The VmCOM component exposes VmServerCt1 and VmCt 1 as the primary objects for communicating with VMware components VmConnect Params VmCollection and VmQuest ion are support objects primary objects AVmServerCt 1 object represen machine enumeration and registra used as inputs or outputs to the methods and properties of the
130. port is 443 for ESX Server 3 machines However the API continues to use port 902 by default when connecting to ESX Server 2 machines When a script needs to connect both to ESX Server 2 and ESX Server 3 machines the port field of the VmPerl VM ConnectionParams should be undef to allow automatic port selection When using the vmware cmd utility omit the O option to allow automatic port selection Symbolic link paths for virtual machine configuration files are supported only for local machines when the API is used to connect to the same machine on which the API runs For more information on using direct path names for configuration files refer to one of these sections depending on which package you use to access the API Using Symbolic Links on page 18 if you are using VmCOM Using Symbolic Links on page 54 if you are using VmPer Using Symbolic Links on page 118 if you are using vmware cmd www vmware com 10 Some performance statistics resource variables are not supported by ESX Server 3 The unsupported variables may still be used when connecting to earlier products The following are the resource variables that are currently not supported by ESX Server 3 Virtual Machine Stats emem cpt tgt emem cptread emem sizetgt emem affinity ecpu affinity edisk vmhba shares Host Stats eSystem mem eSystem mem eSystem mem eSystem mem eSystem mem eSystem mem eSystem mem eSystem mem eSystem mem
131. program included with the VmCOM Scripting API includes a copyright However for brevity we do not include this copyright in its entirety with each sample script and sample program in this manual Instead we include the first line of the copyright followed by ellipses to indicate its placement The complete copyright is as follows Copyright c 1998 2004 VMware Inc Permission is hereby granted free of charge to any person obtaining a copy of the software in this file the Software to deal in the Software without restriction including without limitation the rights to use copy modify merge publish distribute sublicense and or sell copies of the Software and to permit persons to whom the Software is furnished to do so subject to the following conditions The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software The names VMware and VMware Inc must not be used to endorse or promote products derived from the Software without the prior written permission of VMware Inc Products derived from the Software may not be called VMware nor may VMware appear in their name without the prior written permission of VMware Inc THE SOFTWARE IS PROVIDED AS IS WITHOUT WARRANTY OF ANY KIND EXPRESS OR IMPLIED INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT IN NO EVENT SHALL VMWARE INC BE
132. r each syntax in Visual Basic You can individually access each element by passing its index to the Item property or by using the VmCollection lt index as integer gt array syntax in Visual Basic The first element s index is always the integer 1 one Both VmServerCt1 RegisteredVmNames and VmQuestion Choices return a VmCollection of strings The VmCol lection object includes the read only GET properties listed in the following table Property Name Property Type AccessType Description Count integer GET Gets the number of elements in the collection Item lt index as integer gt string GET Gets the element at the specified index 23 VMware Scripting API User s Manual 24 VmCtl The VmCt 1 object represents a virtual machine running on a particular server machine and exposes symbolic constant enumerations properties and methods Properties The VmCt 1 object includes the properties listed in the following table All of the properties can be retrieved GET some of these properties can also be modified PUT Note The last four properties that are lis ed in the following table apply only to ESX Server Property Name Property Type Access Type Description ExecutionState VmExecutionState GET Current state of the virtual machine powered on powered off suspended or stuck For more information on VmExecutionState see VmExecutionState on page 33 PendingQues
133. rd Returns the defined value on success or undef undefined value on failure or if the value is not set Set the value and retry the API call connectparams gt set password password Gets or set the user s password on the server 57 VMware Scripting API User s Manual 58 VMware VmPerl Server The VMware VmPerl Server module represents a VMware server running on a particular machine Method Description server gt connect connectparams Returns the defined value on success or undef undefined value on failure information VMware Vm connect VMware Vm Connects the object to a VMware GSX Server or a VMware ESX Server where connectparams specifies the system and user The total number of connected VMware VmPerl VM and Perl Server objects cannot exceed 62 The method fails with error code VM E INSUFFICIENT RESOURCES if this limit is reached In order to connect new objects destroy one or more connected Perl VM or VMware VYmPerl Server objects server gt get last error Returns the error code and descriptive string Gets details about the last error that occurred in an array of form S error num S Serror string Sserver gt is connected Returns the defined value on success or undef undefined value on failure if the server is not connected or if there is a failure You can use Svm gt get last errorto determine if an error occurred or if
134. red and the choice that was selected as the answer for that message By default the Event Viewer logs all three types of events However you may turn off logging for one or more of these event types by editing the config ini file 1 Change directories to the VMware GSX Server program directory The default location is C Program Files VMware VMware GSX Server 2 Edit the config ini file with a text editor of your choice Add one or more of the following configuration variables Each configuration variable turns off event logging for that event type eventlog win power FALSE eventlog win message FALSE eventlog win answer FALSE Using the Event Viewer 1 Open the Event Viewer application This application is typically in the Administrative Tools folder Refer to your operating system s documentation for additional information on this application 2 Open the Application Log file The Event Viewer is displayed as shown in the following image 111 VMware Scripting API User s Manual l Eve ioj x Action view lt gt EmA Tree Application Log 184 event s Event Viewer Local 1 Date time T source category Event ji Application Log information 5 9 2002 12 17 10PM_VMware GSX Server Virtual machines 1100 Security Log information 5 9 2002 12 16 52 PM VMware GSX Server Virtual machines 1100 t System Log information 5 9 2002 12 16 48 PM VMware GSX Server V
135. rl API package on the service console follow the same procedure as for a Linux installation Refer to Installing VmPerl Scripting API on a Linux Machine on page 15 Installing the VMware Scripting API on a Windows Machine You have a choice of installing either the VmCOM or the VmPerl Scripting API 1 Choose Start gt Run and browse to the directory where you saved the downloaded installer file the name is similar to VMware VmPERLAPI lt xxxx gt exe or VMware VmCOMAPI lt xxxx gt exe where lt xxxx gt is a series of numbers representing the version and build numbers 2 The installer starts Click Next 3 Acknowledge the end user license agreement EULA Select Yes accept the terms in the license agreement then click Next www vmware com 14 CHAPTER 1 Introduction 4 Choose the directory in which to install the Scripting API To install it in a directory other than the default click Change and browse to your directory of choice If the directory does not exist the installer creates it for you Click Next Note Windows and the Microsoft Installer limit the path length to 255 characters for a path to a folder on a local drive and 240 characters for a path to a folder on a mapped or shared drive If the path to the Scripting API program folder exceeds this limit an error message appears You must select or enter a shorter path 5 Click Install The installer begins copying files to your machine 6 Click
136. rogram number Note The cscript command loads the Windows Script Host environment and is included with the supported operating system The js or vbs script contains the program s actual logic The associated wsf file defines and initializes an execution environment for the script In this example the ws file loads VmCOM s type library to allow the script to use VmCOM s symbolic constants For more information on symbolic constants see Properties on page 24 JScript Sample Program 1 This JScript program connects to the local server and lists all registered virtual machines If a virtual machine is in the stuck state the pending question is also displayed The source for the sample program 1 script is in the SampleScripts folder in the VmCOM Scripting API directory You can also find it on the VMware Web site saved with a TXT extension for online viewing at www vmware com support developer scripting APl doc sample 1 js txt VmCOM JScript Sample Script samplel Copyright c 1998 2004 VMware Inc This program is for educational purposes only It is not to be used in production environments Description www vmware com CHAPTER 3 Using Sample VmCOM Programs This script displays the virtual machines on the local server It prints the configuration file path and current execution state of each VM If a VM is in the stuck state the current question and its choices are also printed
137. rosoft Visual C and JScript You may install the VmCOM Scripting API on machines with the Microsoft Windows operating system VmPerl is an application programming interface API that utilizes the Perl scripting language You may install the VmPerl Scripting API on machines with the Microsoft Windows or Linux operating system VMware Scripting API User s Manual Introducing the VMware Scripting APIs You may install the Scripting APIs on the GSX Server host and on remote workstations connecting to GSX Server or ESX Server E VmCOM q VmpPerl k i a q GSX Server on a Windows hosi Windows remote workstation ESX Server GSX Server on a Linux host Linux remote workstation Although the interfaces for VmCOM and VmPerl are different both components are functionally equivalent Depending on your operating system you can either use VmCOM or VmPerl to accomplish the same tasks VMware has designed VmCOM and VmPerl to provide task automation and simple single purpose user interfaces The Scripting APIs are not intended for building advanced interactive user interfaces For example you can use the VMware Scripting APIs to perform power operations start stop suspend or reset on VMware servers and virtual machines locally and remotely across servers You can also use the API to register and unregister virtual machines and gather information about them including sending and receiving configura
138. s For example you keep the virtual disk of a virtual machine in undoable mode At some point you may want to commit your changes and back up the entire contents of the virtual disk You can add a second new redo log using the vm gt add redo method The original redo log is no longer changing all data is now written to the new redo log You can then commit the original redo log to the base virtual disk by using the vm gt commit method with level with a value of 1 The presence of the second redo log allows you to commit changes from the original redo log to the virtual disk without freezing the virtual disk Once the commit is done you can back up the virtual disk For more information about the vm gt commit method please see VMware VmPerl VM on page 60 This script commitnext p1 saved with a TXT extension for online viewing can be found on the VMware Web site at www vmware com support developer scripting APl doc commitnext pl txt Note This script applies only to ESX Server 1 x and 2 x usr bin perl w Copyright C 1998 2004 VMware Inc commitnext pl This script takes a specification of a server name user password and the path for the config file of a virtual machine on that server It then displays the disks in the virtual machine 103 VMware Scripting API User s Manual configuration and allows the user to choose a disk It then commits the next to
139. s a server and exports server level services such as virtual ion A VmCt 1 object represents a virtual machine on a particular server and provides virtual machine specific methods such as power operations You must first activate the VmServerCt1 or Vmct 1 object by calling its Connect method before accessing any other method The Connect method requires a VmConnect Params input parameter containing the host identifier and user credentials supp ied for authentication If the host identifier is not supplied or is undefined the authentication is performed on the local system If the user name and password are also not supplied the current user is authenticated on the local machine Otherwise you may supply the user name and password for authentication as that user Unlike the VmServerCt1 object VmCt 1 Connect also takes a string specifying the configuration file name of the virtual machine that will be connected 17 VMware Scripting API User s Manual 18 Once a VmServerCt1 object is connected you can enumerate the virtual machines on the server and register or unregister the virtual machines You can obtain a list of virtual machines on a particular server from the VmserverCt 1 RegisteredVmNames property This property returns a collection object named VmCollect ion The collection s elements comprise virtual machine configuration file names and you can enumerate these elements using for example the for ea
140. scription System Statistics system sys cosUptime VMware Service Console uptime in seconds system sys vmkUptime T VMkernel uptime in seconds CPU Statistics system cpu number T Number of CPUs on the ESX Server system On hyperthreading enabled systems this number of CPUs reflects the number of logical CPUs double the number of physical CPUs system cpu T Information about the CPU specified by 4 system cpu idlesec FLOAT Idle time in seconds of the physical or logical CPU specified by system cpu usedsec FLOAT Time in seconds the physical or logical CPU specified by is in use Memory Statistics system mem avail T Amount of memory in KB available for all virtual machines system mem COS T Amount of memory in KB allocated to the service console system mem COSavail T Amount of free memory in KB available to the service console Note This is not supported in ESX Server 3 system mem active T Amount of memory subset of system mem size that has been recently used system mem cosUsage T Amount of memory in KB currently used by the service console The Note This is not supported in ESX sum of system mem COSavail and system mem cosUsage should Server 3 equal the value for system mem COS system mem cpt tgt NT Total amount of data in KB read from suspend files for all virtual Note This is not supported in ESX machines Server 3
141. side a virtual machine you can pass information from a script running in another machine to the guest operating system and from the guest operating system back to the script through the VMware Tools service You do this by using a class of shared variables commonly referred to as Guestlnfo VMware Tools must be installed and running in the guest operating system before a Guestinfo variable can be read or written inside the guest operating system For example create and connect a VMware VmPerl VM object assuming the virtual machine is powered off Next set the Guestinfo variable with the VmPerl API Then power on the virtual machine and use the VMware Tools service to retrieve the variable See Sending Information Set in a VmPerl Script to the Guest Operating System on page 74 for an example of this procedure See your VMware product documentation for more information about VMware Tools Guestinfo Variables You pass to the virtual machine variables you define yourself What you pass is up to you but you might find it useful to pass items like the virtual machine s IP address Windows system ID SID for Windows guest operating systems or machine name This is useful in situations where you want to deploy virtual machines on a network using a common configuration file while providing each machine with its own unique identity By providing each virtual machine with a unique identifying string you can use the same configuration f
142. sing information between a script and a guest operating system see Using VmPerl to Pass User Defined Information Between a Running Guest Operating System and a Script on page 73 This script getguestip p1 saved with a TXT extension for online viewing can be found on the VMware Web site at www vmware com support developer scripting APl doc getguestip pl txt usr bin perl w Copyright C 1998 2004 VMware Inc getguestip pl This script returns the value of the guest info variable ip set by the guest OS in a virtual machine on a given server usage getguestip pl lt path to config file gt lt server gt lt user gt lt password gt BEGIN if 0 eq MSWin32 INC Set the path to your VmPerl Scripting directory if different C Program Files VMware VMware VmPerl Scripting API perl5 site perl 5 005 C Program Files VMware VMware VmPerl Scripting API per15 site_perl 5 005 MSWin32 x86 use VMware VmPerl use VMware VmPerl VM use VMware VmPerl ConnectParams use strict if ARGV ne 1 amp amp ARGV ne 4 99 VMware Scripting API User s Manual 100 print Usage 0 lt path to config file gt lt server gt lt user gt lt password gt n exit 1 Read in parameters my Scfg path Sserver name user Spasswd ARGV Use the default port Change this if you need to specify a port my Sport undef If server name user a
143. status on off suspended of the virtual machine specified by config on the server defined by hostname usage status pl lt path_to_config file gt lt server gt lt user gt lt password gt If server user and password are not given connect to the local server as the current user BEGIN if O0 eq MSWin32 INC Set the path to your VmPerl Scripting directory if different C Program Files VMware VMware VmPerl Scripting API perl5 site perl 5 005 C Program Files VMware VMware VmPerl Scripting API perl15 site_perl1 5 005 MSWin32 x86 use VMware VmPerl use VMware VmPerl VM use VMware VmPerl ConnectParams use strict Retrieves a pre defined constant value sub vm_constant my Sconstant_str shift return VMware VmPerl constant constant_str 0 85 VMware Scripting API User s Manual if ARGV lt 1 print Usage 0 lt path to config file gt lt server gt lt user gt lt password gt n exit 1 my state string map my state_strings VM_EXECUTION STATE ON VM_EXECUTION STATE OFF VM_EXECUTION STATE SUSPENDED VM_EXECUTION STATE STUCK VM_EXECUTION STATE UNKNOWN foreach my state_string state_strings state_string_map gt vm_constant state_string state_string Read in parameters my cfg_path server_name user Spasswd ARGV Use the default port Change this if you need to specify a port
144. t get id Gets an integer used internally by VmPerl to identify the question Returns the defined value on success or undef undefined value on failure 69 VMware Scripting API User s Manual 70 Symbolic Constants The VMware VmPerl VM object exposes the following symbolic constants VM_EXECUTION_STATE_ lt XXX gt Values VM POWEROP MODE lt XXX gt Values Infotype Values VM PRODINFO PRODUCT lt XXX gt Values VM PRODINFO PLATFORM lt XXX gt Values VM EXECUTION STATE lt XXX gt Values VM EXECUTION STATE lt XXX gt values specify the state or condition of a virtual machine The possible values are listed in the following table Execution state Values Description VM EXECUTION STATE ON The virtual machine is powered on VM EXECUTION STATE OFF The virtual machine is powered off VM EXECUTION STATE SUSPENDED The virtual machine is suspended VM EXECUTION STATE STUCK The virtual machine requires user input The user must answer a question or dismiss an error VM EXECUTION STATE UNKNOWN The virtual machine is in an unknown state VM POWEROP MODE lt XXX gt Values VMware VmPerl VM POWEROP MODE lt XXX gt specifies the behavior of a power transition start stop reset or suspend method If Smode is not specified the default mode is VM POWEROP MODE SOFT However if you are connecting to GSX Server 1 x or ESX Server
145. t is typically incremented at least once per second when the VMware Tools service is running under light load conditions The count stays constant if the service is not running vm gt get_tools_last_active Returns the defined value on success or undef undefined value on failure Returns an integer indicating how much time has passed in seconds since the last heartbeat was detected from the VMware Tools service This value is initialized to zero when the virtual machine powers on It stays at zero until the first heartbeat is detected after which the value is always greater than zero until the virtual machine is power cycled again For additional information see Additional Information on get_tools_last_active on page 67 vm gt get_pending_question Returns the defined value on success or undef undefined value on failure Returns a Vmware VmPerl Question object if the virtual machine is currently in the VM_EXECUTION_STATE_STUCK state Use Squestion gt get text to retrieve the actual question text For additional information see VMware VmPerl Question on page 69 65 VMware Scripting API User s Manual Method Description vm gt answer question Squestion choice Returns the defined value on success or undef undefined value on failure vm gt device is connected Sdev name Returns the defined value on success or false on failure if the device is not connected or
146. t where noted otherwise these methods are synchronous the method does not return until it finishes its operation fails or times out Most operations time out after 2 minutes except for power operations which time out after 4 minutes Note Two methods object AddRedoandobject Commit that are listed in the following table apply only to ESX Server 1 x and 2 x Similarly the object SetRunAsUser and object RunAsUser methods apply only to GSX Server Method Description object Connect lt params gt lt vmName gt The Connect method establishes a connection with a virtual machine where params is a VnConnect Params object that specifies the system and user information and vmName is a string specifying the virtual machine s configuration file name You should use this as the first method invoked on a VmCt 1 object You must first activate the VmCt 1 object by calling its Connect method before accessing any other method or property There is no method to disconnect from a virtual machine To reconnect to a different virtual machine destroy the VmCt 1 object create a new one then call its Connect method The total number of connected VmCt 1 and VmServerct 1 objects cannot exceed 62 The Connect method fails with error code vmErr INSUFFICIENT RESOURCES if this limit is reached In order to connect new objects destroy one or more connected VmCt 1 or VmServerCt1 objects For example you can do this by setting an
147. tate of the virtual machine to a suspend file For more information see VmPowerOpMode on page 33 This method always fails if the virtual machine is not in the vmExecutionsState On state object AddRedo lt diskDevName gt Note This method applies only to ESX Server 2 and earlier This method adds a redo log to a running virtual SCSI disk specified by lt diskDevName gt that is associated with the virtual machine specified by the VmCt 1 object Changes made to the virtual disk accumulate in the new redo log This disk must be an ESX Server virtual disk stored on a VMFS volume lt diskDevName is a string containing the disk device name The format of the disk device name is explained in the section Disk Device Names on page 19 The virtual disk can be in persistent undoable or append mode The redo log for a virtual disk in persistent mode uses the file name of the virtual disk with REDO appended to it for example if the disk is called vm dsk the redo log is called vm dsk REDO A virtual disk in undoable or append mode already has a redo log associated with it so the new redo log you create is called vm dsk REDO REDO whose parent is the existing redo log vm dsk REDO This method fails if the specified virtual disk does not exist the specified virtual disk is in nonpersistent mode an online commit is already in progress or the virtual disk already has two redo logs associated with it If you
148. ter than zero until the virtual machine is power cycled again vmware cmd lt vm cfg path gt answer Prompts the user to answer a question for a virtual machine waiting for user input vmware cmd getresource lt vm cfg path gt lt variable_name gt Note This method applies only to ESX Server Gets the value of the virtual machine resource variable specified by lt variable_name gt For a list of ESX Server virtual machine resource variables see Virtual Machine Resource Variables for ESX Server on page 135 vmware cmd setresource lt vm cfg path gt lt variable_name gt lt value gt Note This method applies only to ESX Server Sets the value of the virtual machine resource variable specified by lt variable_name gt For a list of ESX Server virtual machine resource variables see Virtual Machine Resource Variables for ESX Server on page 135 vmware cmd lt vm cfg path gt getuptime Note This method applies only to ESX Server 2 and earlier Accesses the uptime of the guest operating system on the virtual machine vmware cmd lt vm cfg path gt getid Returns a unique ID for a running virtual machine 123 VMware Scripting API User s Manual 124 Virtual Machine Operation Description vmware cmd lt vm cfg path gt getpid Note This method applies only to ESX Server 2 and earlier Returns the process ID of a running virtual machine vmware cmd lt vm c
149. th a TXT extension for online viewing can be found on the VMware Web site at www vmware com support developer scripting API doc suspend pl txt usr bin perl w Copyright C 1998 2004 VMware Inc This script suspends to disk the virtual machine specified by config on the server defined by hostname usage suspend pl suspend pl hostname user password config BEGIN if O0 eq MSWin32 INC Set the path to your VmPerl Scripting directory if different C Program Files VMware VMware VmPerl Scripting API perl5 site perl 5 005 C Program Files VMware VMware VmPerl Scripting API per15 site_perl 5 005 MSWin32 x86 use VMware VmPerl use VMware VmPerl VM use VMware VmPerl ConnectParams use strict if ARGV lt 1 print Usage 0 lt path to config file gt lt server gt lt user gt lt password gt n exit 1 my Scfg path Sserver name user Spasswd ARGV Use the default port Change this if you need to specify a port my Sport undef Connect to the local host on the default port as yourself www vmware com CHAPTER 5 Using Sample VmPerl Scripts my S connect_params VMware VmPerl ConnectParams new server name port user passwd Create a new VMware VmPerl VM object to interact with a virtual machine my vm VMware VmPerl VM new Establish a persistent connection with virtual machine i
150. the server is not connected Use this met hod to determine whether or not a connection exists to the server specified by server The remaining methods only work after you connect to the server with server gt connect Note Two methods server gt get_resourceand server gt set_resource that are listed in the following table apply only to ESX Server Method Description Sserver gt registered_vm_names Returns a list of virtual machine configuration file names an empty list if no virtual machines are registered or if there is a failure You can use vm gt get_last_error to determine if an error occurred or there are no registered virtual machines Gets an array of strings specifying the configuration file names of the virtual machines currently registered on the server The array is indexed beginning at 0 zero The server must be connected using the connect method or this method throws an error Sserver gt register_vm vm_name Returns the defined value on success or undef undefined value on failure Registers a virtual machine on a server where vm_name is a string specifying the virtual machine s configuration file name www vmware com CHAPTER 4 Using VmPerl Method Description server gt unregister_vm Svm_name Retu und rns the defined value on success or undef efined value on failure Unregisters a virtual machine
151. tion VmQuestion GET Returns a VmQuestion object if the virtual machine is currently in the vmExecutionState_Stuck state Otherwise an error is thrown GuestInfo keyName string GET PUT Accesses a shared variable identified by the string keyName For additional information see Using VmCOM to Pass User Defined Information Between a Running Guest Operating System and a Script on page 36 Config keyName string GET PUT Accesses the value of a configuration variable identified by the string keyName When a virtual machine process is spawned on the server the process reads configuration variables from the virtual machine s configuration file into memory If you write a configuration variable by using the Config property the new value is written into memory and is discarded when the virtual machine process terminates You cannot change the value of a configuration variable in a virtual machine s configuration file The property throws an error if it accesses an undefined configuration variable Do not change the memory size while a virtual machine is suspended First power off the virtual machine then change its memory size www vmware com CHAPTER 2 Using VmCOM Property Name Property Type Access Type Description ConfigF ileName string GET Returns the configuration file name for the virtual machine This method fails if the VmCtl object is not conn
152. tion 65 get pid 67 get port 56 get product info 65 71 72 get remote connections 67 get resource 59 67 get text 65 69 get tools last active 65 67 get uptime 67 get username 56 has snapshot 64 is connected 58 60 D 143 144 register_vm 58 registered vm names 54 58 remove snapshot 64 reset 61 revert to snapshot 64 set config 65 66 set guest info 64 74 set resource 59 67 start 61 stop 61 suspend 62 unregister vm 59 MiniMUI Visual Basic project 15 41 N network failure 109 network port 56 network statistics 133 138 139 no response 110 not enough memory 109 P passing information between script and guest operating system 36 38 73 75 password 20 56 PendingQuestion property 24 30 32 108 permission 109 Pid property 25 platform 35 72 123 platform information 35 port 20 56 116 power status of a virtual machine 24 64 85 86 119 power transition 33 70 111 113 hard 34 71 125 invalid 109 soft 34 71 125 trysoft 34 71 125 powering off a virtual machine 27 33 34 61 70 71 119 125 powering on a virtual machine 27 33 34 61 70 71 119 125 process ID for a running virtual machine 25 67 124 product information 25 34 35 65 71 72 123 Productinfo property 25 property Capabilities 26 Choices 23 30 32 Config 24 31 ConfigFileName 25 Count 23 DevicelsConnected 25 ExecutionState 24 Guestinfo 24 Heartbe
153. tion to a virtual machine You can also send properties you define from the host or a script into a virtual machine s guest operating system and vice versa We provide example scripts and applications demonstrating possible uses for the Scripting APIs The directory in which you installed VmCOM contains two subdirectories MiniMUI that contains a sample Visual Basic project that uses VmCOM and SampleScripts that contains sample VmCOM scripts Similarly the directory in which you installed VmPerl contains a subdirectory SampleScripts that contains sample VmPerl scripts Supported Products We support the installation of the VmCOM and VmPerl Scripting APIs on the following products www vmware com CHAPTER 1 Introduction GSX Server 2 x GSX Server 3 x ESX Server 2 x ESX Server 3 For more information see the product documentation Web pages at www vmware com support pubs gsx_pubs html GSX Server www vmware com support pubs esx_pubs html ESX Server 2 x www vmware com support pubs vi_pubs html ESX Server 3 Intended Audience This manual is written for programmers that are familiar with either the Perl language or the Component Object Model COM interface for programming languages Readers of this manual should be comfortable with developing system administration and system monitoring programs and general debugging techniques In addition developers who use this manual should be familiar with the operation and management of
154. tions You activate the VMware VmPerl Server or VMware VmPerl VM object by calling its connect method before accessing any other method The connect method requires a connect params input parameter containing the host identifier and user credentials supplied for authentication If the host identifier is not supplied or is undefined the authentication is performed on the local system If the user name and password are also not supplied the current user is authenticated on the local machine Otherwise you may supply the user name and password for authentication as that user Unlike a VMware VmPerl Server object vm gt connect also takes the string vm_name specifying the configuration file name of the virtual machine that will be connected Once a VMware VmPerl Server object is connected you can enumerate the virtual machines on the server and register or unregister the virtual machines You can obtain a list of virtual machines on a particular server by using the server gt registered_vm_names method This method returns an array of strings specifying the configuration file names of the virtual machines currently registered on the server If you know the configuration file name of a specific virtual machine you can connect the VMware VmPerl VM object directly without using a VMware VmPerl Server object Using Symbolic Links Many Scripting API operations require you to supply a path to a virtual machine used in the operat
155. to the virtual machine s configuration file and start is the power operation Since a lt powerop mode gt is not specified the default soft behavior is performed Similarly in a Windows guest operating system vmware cmd q C home vmware win2000 vmx reset hard where q indicates the quiet option only the results of the operation are printed C home vmware win2000 vmx is the path to the virtual machine s configuration file and reset is the power operation This example specifies a hard reset so the virtual machine is immediately and unconditionally reset www vmware com CHAPTER 7 vmware cmd Utility Setting a Configuration Variable The following example illustrates setting a configuration variable in a Linux guest operating system Change directories to the directory folder containing the vmware cmd utility or include the full path to the utility when typing the following on a command line vmware cmd foo vmx setconfig idel 0 file tmp cdimages foo iso where foo vmx is the virtual machine s configuration file ide1 0 file is the variable and its value is tmp cdimages foo iso Connecting a Device The following example illustrates connecting a virtual IDE device in a Windows guest operating system Change directories to the directory folder containing the vmware cmd utility or include the full path to the utility when typing the following on a command line Note that you must use double quotes when specifying
156. transmitted Miscellaneous Statistics system worlds string Space delimited set of IDs listing running virtual machines Note This is not supported in ESX Server 3 system net adapters string Space delimited set of identifiers for bonds and physical network adapters for example bondo orvmnet 0 133 VMware Scripting API User s Manual 134 Variable Name Variable Type Description system disk HTL string Space delimited set of disks specified as a set of host target LUN HTL for example vmhba0 0 0 or vmhba1 0 1 www vmware com CHAPTER 8 VMware ESX Server Resource Variables Virtual Machine Resource Variables for ESX Server Use these variables to return or set resource statistics on virtual machines running on ESX Server For more information on the VmCOM resource property see VmCtl on page 24 For more information on the VmPerl get resource and set resource methods see VMware VYmPerl VM on page 60 In the following table lt HTL gt represents the host target LUN for a SCSI device that is assigned to a particular virtual machine For example for vmhba1 2 0 1 represents the host adapter 2 represents the target on the adapter and 0 specifies the LUN Similarly lt MAC gt represents the media access control MAC address for virtual network adapters The virtual machine session lasts until all remote connections are closed including remote consoles and remote c
157. tual machine on the target device specified by lt HTL gt disk lt HTL gt busResets T umber of bus resets that occurred on the target device specified by lt HTL gt due to a command from the virtual machine disk lt HTL gt cmds T Total number of commands made by the virtual machine on Note This is not supported in ESX he target device specified by lt HTL gt Server 3 disk lt HTL gt cmdsAborted T Total number of commands made by the virtual machine that Note This is not supported in ESX were aborted on the target device specified by lt HTL gt Server 3 disk lt HTL gt reads T Total number of disk reads for the virtual machine on the target device specified by lt HTL gt disk lt HTL gt writes T Total number of disk writes for the virtual machine on the arget device specified by lt HTL gt disk lt HTL gt shares T Number of disk shares assigned to the virtual machine on the Note This is not supported in ESX Read write arget device specified by lt HTL gt Network Statistics 138 www vmware com CHAPTER 8 VMware ESX Server Resource Variables Variable Name Variable Type Description net adapters string Space delimited set of identifiers for virtual network adapters In ESX Server 3 these identifiers are numeric in other products these identifiers are the MAC addresses corresponding to the virtual network adapters net lt mac gt totKBRx INT Total amount of data received in
158. ue may occasionally reach several seconds If the service stops running either because the guest operating system has experienced a failure or CHAPTER 4 Using VmPerl 67 VMware Scripting API User s Manual 68 the guest has been down The following table summarizes how you may interpret the get tools last active method values get tools last active Method Value Description 0 The VMware Tools service has not started since the power on of the virtual machine 1 The VMware Tools service is running and is healthy 2 3 4 0r5 The VMware Tools service could be running but the guest operating system may be heavily loaded or is experiencing temporary problems Greater than 5 The VMware Tools service stopped running possibly because the guest operating system experienced a fatal failure is restarting or is shutting down www vmware com CHAPTER 4 Using VmPerl VMware VmPerl Question The VMware VmPerl Question method describes a question or error condition requiring input The script selects one from the list of possible answers Method Description Squestion gt get_text Gets the question text Returns the defined value on success or undef undefined value on failure Squestion gt get choices Gets an array of strings representing a list of possible answers to the Returns the defined value on success or undef question undefined value on failure Squestion g
159. unt of usedsec cumulative processor time in milliseconds consumed by the virtual CPU over and above the value guaranteed by emin cpu syssec FLOAT Amount of CPU time in milliseconds used by the VMkernel on behalf of the virtual machine for example for I O processing This CPU time is included in usedsec described later in this table cpu uptime Note This is not supported in ESX Server 3 INT Amount of elapsed time in seconds since the virtual machine was powered on cpu usedsec INT Number of seconds of CPU time used by a virtual machine Note For an SMP virtual machine this variable reports only the amount used by virtual CPU 0 To report the total used by all virtual CPUs calculate the sum of all cpu lt n gt usedsec variables where lt n gt is the number of virtual CPUs returned by the cpu number variable cpu waitsec FLOAT Number of milliseconds that a virtual machine is idle or blocked on some event cpu affinity Note This is not supported in ESX Server 3 string Read write CPU affinity set as a comma delimited set of numbers with each number referring to a CPU number For example if a CPU affinity set is O 1 3 then a virtual machine runs on CPU 0 1 or 3 cpu htSharing string Read write Specifies how the virtual CPUs in a virtual machine are allowed to share physical packages on a hyperthreaded system The values are any Default
160. use only the VmPerl API Using the Server Object You can query virtual machine resource values by using either the virtual machine object or the server object For the latter the resource value string used in the query must be qualified with the virtual machine s world ID number For example if a virtual machine s ID is 131 then the following VmPerl queries return identical values Sserver gt get_resource vm 131 cpu usedsec Svm gt get resource cpu usedsec However querying through the virtual machine object has slightly more overhead than querying through the server object so we recommend that you use the server object Reusing a Single Server Object There is some overhead associated with creating and connecting a server object or a virtual machine object Therefore if you expect to query system or virtual machine resource values very frequently then we recommend you perform all queries using a single connected server object For example in VmPerl one time setup of server object my conn params VMware VmPerl ConnectParams new server_name Sport user Spasswd my Sserver VMware VmPerl Server new server gt connect conn_params query system vm resources server gt get resource system worlds server gt get resource vm lt gt one time teardown of server object Sserver gt disconnect www vmware com Index Symbols Schoice 66 Sconnectparams 54
161. uspend 28 vmErr_BADSTATE 31 109 vmErr BADVERSION 109 vmErr DISCONNECT 108 109 vmErr INSUFFICIENT RESOURCES 22 27 109 vmErr INVALIDARGS 109 vmErr INVALIDVM 109 vmErr NEEDINPUT 108 109 vmErr NETFAIL 109 vmErr NOACCESS 109 vmErr NOMEM 109 vmErr NOPROPERTY 109 VmErr vm vm vm vm vm vm vm vm OSUCHVM 110 OTCONNECTED 108 110 Err NOTSUPPORTED 110 Err PROXYFAIL 110 Err TIMEOUT 110 Err UNSPECIFIED 110 Err VMBUSY 110 Err VMEXISTS 110 Err VMINITFAILED 110 Err VmExecutionState 33 vm ame 27 VmpPerl add redo method 62 answer question method 66 commit method 63 concepts 53 connect method 54 58 60 109 connect_device method 66 create_snapshot method 63 device_is_connected method 66 disconnect_device method 66 error handling 108 get_capabilities method 67 get_choices method 66 69 get_config method 65 get_config_file_name method 64 get_connected_users method 64 get_execution_state method 64 get_guest_info method 64 75 get_heartbeat method 65 get_hostname method 56 get_id method 67 69 get_last_error method 58 60 66 108 get_password method 57 get_pending_question method 65 get_pid method 67 get_port method 56 get_product_info method 65 71 72 get_remote_connections method 67 get_resource method 59 67 get_text method 65 69 get_tools_last_active method 65 67 get_uptime method
162. w methods such as create_snapshot These methods are only supported on ESX Server 3 At the same time the methods that implement redo log functionality add_redo and commit are not supported on ESX Server 3 Disk Device Names For certain operations you need to specify a virtual disk Virtual disks are specified from the perspective of the virtual machine using the virtual controller number and the virtual SCSI device number The disk device name is a string in the format scsi lt m gt lt n gt where lt m gt is the virtual controller number and lt n gt is the virtual SCSI device number Each virtual disk has a unique combination of virtual controller number and virtual device number that compose the disk device name If you know the name of the virtual disk file you can locate the corresponding numbers in the virtual machine s configuration file To determine the numbers in the disk device name view the contents of the virtual machine configuration file For each virtual disk belonging to the virtual machine the configuration file contains a line identifying the virtual disk file that acts as the backing store for the virtual SCSI disk You use this line to find the numbers belonging to the file name of the virtual disk For example if the configuration file contains the following line scsi0 1 name My VMFS My VM disk 2 vmdk then you know that the disk device name forMy VM disk 2is scsio 1 representing virtual SCS
163. y to ESX Server 3 Returns the process ID of a running virtual machine vm gt get_capabilities Note This method applies only to ESX Server 2 and earlier Returns the access permissions for the current user This number is a bit vector where 4 read 2 write and 1 execute For a user with all three permissions a value of 7 is returned when this property is used in a script vm gt get_remote_connections Note This method applies only to ESX Server 2 and earlier Returns the number of remotely connected users This value includes the number of remote consoles Scripting APIs and Web based management interface connections to the virtual machine vm gt set_runas_user Suser password Note This method applies only to GSX Server 3 1 Runs the virtual machine as the user specified by the user and password vm gt get_runas_user Note This method applies only to GSX Server 3 1 Returns the name of the user running the virtual machine Additional Information on If the guest operating system is heavi get_tools_last_active is shutting down the value keeps increasing You can use a script with the get tools last active method to monitor the start of the VMware Tools service and once started the health of the guest operating system If the guest operating system has failed the get_tools_last_active method indicates how long ly loaded this val
Download Pdf Manuals
Related Search
Related Contents
T-300 Instructions Prise en charge des patients sous substitution rénale – 1re partie Sony XM-D400P5 Product Guide OccuSwitch DALI User Manual 取扱説明書 - Dynabook Avaya 1220 with SIP Software 4.0 User Guide Copyright © All rights reserved.
Failed to retrieve file