Chapter 8. Scripting and Automation with the vCLI

When VMware first released ESXi 3.5, the Remote Command Line Interface (RCLI) was also introduced to provide a replacement mechanism for administrators accustomed to using the Service Console on ESX. Significant improvements have been made in the last two releases of this interface, and with the release of vSphere the RCLI was renamed to the vSphere Command Line Interface (vCLI). The vCLI is available for both Linux and Windows.

VMware also created a virtual appliance called the vSphere Management Assistant (vMA). The vMA includes the vCLI and adds the vi-fastpass authentication component and the vi-logger component. The vi-fastpass component eliminates the need to supply credentials when executing vCLI commands, whereas the logging component captures log files from ESXi for further analysis.

Both the vCLI installation package and the vMA include the vSphere Software Development Kit (SDK) for Perl. The vSphere SDK for Perl provides an easy-to-use Perl scripting interface to the vSphere application programming interface (API). A number of sample scripts are included, and you can use the SDK to build utilities to configure and manage your ESXi hosts. The vSphere SDK for Perl includes the Web Services for Management (WSMAN) component, which can be used to create scripts that retrieve health data from ESXi hosts and vCenter Server.

This chapter examines the following items:

  • Installing the vCLI on Linux and Windows

  • Importing and configuring the vMA

  • Using the commands of the vCLI

  • Using the authentication and logging components of the vMA

Installing the vCLI on Linux and Windows

The installation of the vCLI includes both the vCLI commands and the vSphere SDK for Perl. For Windows installations, these components and a number of required components are all included in the installation package. For Linux, the following prerequisite packages are required before the installer can proceed:

  • OpenSSL. This component is used to provide Secure Sockets Layer (SSL) communications with the vSphere API running on ESXi and vCenter Server.

  • LibXML2. This package is required for Extensible Markup Language (XML) parsing.

  • e2fsprogs. This package contains utilities for maintaining ext2, ext3, and ext4 filesystems. It is required by the Universally Unique Identifier (UUID) Perl Module, which the vCLI package installs if it does not find it on the system.

If you start the Linux installer and any of these packages are missing, it reports an error and terminates the installation. On a Red Hat Linux machine, you can install OpenSSL and LibXML2 with the following command:

yum install openssl-devel libxml2-dev

For other Linux distributions, you can consult your documentation for the appropriate installation command.

The Linux installer for the vCLI also checks for the following components:

  • Crypt_SSLeay_0.55 (0.55_0.9.7 or 0.55_0.9.8)

  • IO_Compress_Base_2.005

  • Compress_Zlib_2.005

  • IO_Compress_Zlib_2.005

  • Compress_Raw_Zlib_2.017

  • Archive_Zip_1.26

  • Data_Dumper_2.121

  • XML_LibXML_1.63

  • libwww_perl_5.805

  • XML_LibXML_Common_0.13

  • XML_NamespaceSupport_1.09

  • XML_SAX_0.16

  • Data_Dump_1.15

  • URI_1.37

  • UUID_0.03

  • SOAP_Lite_0.710.08

  • HTML_Parser_3.60

  • version_0.78

If any of these components is not found, the vCLI installer adds the package to your system. If a different version is found on your system, the installer still proceeds. At the end of the installation process, the installer informs you that the correct version of the component is not installed and specifies the version that the vCLI was tested with.

You can download the latest release of the vCLI from the following Web uniform resource locator (URL): http://www.vmware.com/support/developer/vcli/. You can use the following steps to install the vCLI on your Linux computer:

  1. Uninstall an existing version of the vCLI or RCLI with the command /usr/bin/vmare-uninstall-vSphere-CLI.pl.

  2. Extract the vCLI download with this command: tar /zxvf VMware-vSphere-CLI--4. 1-0-254719.x86_64.tar.gz. This creates the folder vmware-vsphere-cli-distrib.

  3. Ensure that you are logged in as a superuser and start the installation with the command sudo vmware-vsphere-cli-distrib/vmware-install.pl.

  4. Type yes and press Enter to accept the license terms.

  5. Specify an installation folder or accept the default of /usr/bin.

If the installer detected an incorrect version for the components listed previously, a warning message is displayed. Otherwise, a success message is shown and you are returned to the command prompt. With the default installation, the components of the vCLI can be found in the following locations:

  • vCLI scripts: /usr/bin

  • vSphere SDK for Perl utility applications: /usr/lib/vmware-vcli/apps

  • vSphere SDK for Perl sample scripts: /usr/share/doc/vmware-vcli/samples

Tip

If you uninstall a prior version of the vCLI and then install the vCLI to a different folder, you must reset the PATH environment variable. You can do this before or after upgrading the vCLI. If you do not update the path, the system may search the old location for vCLI commands.

The vCLI installation for Windows can be downloaded from the link provided earlier. It includes the ActivePerl runtime from ActiveState Software and the required Perl modules. The vCLI is supported on the 32-bit versions of Windows XP, Vista, and 2003 and the 64-bit version of Windows 2008.

Use the following steps to install the vCLI on a Windows computer:

  1. Start the installation package for the vCLI. If a prior version is detected, it is automatically uninstalled.

  2. Click Next on the Welcome screen to proceed.

  3. Accept the license agreement and click Next.

  4. Select the installation folder and click Next.

  5. Click Install to begin the installation.

  6. Click Finish to complete the installation.

The vCLI installation on Windows makes changes to the system path. You should log off and back in again to pick up those changes before testing your installation. The components of the vCLI are installed to the following locations with a default installation. The folder where the vCLI scripts are located is not added to the system path. When you attempt to run those commands, you should either make that your current directory in the command prompt or add the bin folder to the system path.

  • vCLI scripts: C:Program FilesVMwareVMware vSphere CLIin

  • vSphere SDK for Perl utility applications: C:Program FilesVMwareVMware vSphere CLI Perlapps

  • vSphere SDK for Perl sample scripts: C:Program FilesVMwareVMware vSphere CLIPerl samples

Tip

The commands included with the vCLI are Perl scripts and when executed on Windows require the addition of the .pl extension. The samples in this chapter do not include the extension, but you need to include it when running the vCLI on Windows. The exception is for esxcli, which is a precompiled executable.

After you install the vCLI, you can quickly test your installation to ensure that it has installed correctly. Open a command prompt and then navigate to the bin folder on your Linux or Windows system. vCLI command scripts follow this format:

<command> <connection_options> <parameters>

To view the virtual machines registered on an ESXi host, you can run the following command:

vmware-cmd --server esx01 -l

You will be prompted for a login and password. If the command is entered correctly, a list of virtual machines is displayed. If you have made an error with the command, the help file showing the command syntax is displayed.

Note

Although the vCLI allows configuration of Internet Protocol Version 6 (IPv6) on your ESXi hosts, communication with the hosts is supported only on Internet Protocol Version 4 (IPv4).

Installing and Configuring the vMA

The vMA is a CentOS-based virtual machine that includes the vCLI and vSphere SDK for Perl. It also extends the vCLI with an authentication component that allows you to run scripts against ESXi or vCenter Server without authenticating each command and a logging component for gathering ESXi and vCenter Server logs. The vMA can be joined to your Active Directory domain, which eliminates the need to maintain local accounts and enables you to pass your credentials through to the ESXi and vCenter Server hosts that you interact with.

The vMA comes preconfigured with the following two user accounts: vi-admin and vi-user. With the vi-admin account, you can perform administrative operations on the vMA such as adding target servers for the authentication component. The vCLI commands that you run with this account also execute with administrative privileges on the added target hosts. The vi-user account is disabled by default. When enabled, it can be used to run vCLI commands but those execute only with read-only privileges on the target hosts. The root account does exist in the vMA, but it is disabled. To run privileged commands, you can use sudo and by default this is limited to the vi-admin account. Sudo (super user do) allows users to run programs with the security rights of another user, which in this case is the root account. Throughout this chapter, a number of examples are shown where sudo is required.

As it is packaged as a virtual machine, the vMA can be run on an ESXi or any other VMware product. The guest operating system (OS) is 64-bit so the host must be capable of running 64-bit guests. The vMA does include VMware Tools, so you can control the power state of the vMA just as you would with any other virtual machine.

Included with the vMA is a Simple Network Management Procotol (SNMP) server that enables monitoring of the vMA. The vMA can’t proxy SNMP data about the hosts it manages or export a configuration using SNMP. The SNMP Management Information Bases (MIBs) included with the vMA allow you to gather data about the vMA host, including its resources, resource usage, and networking setup.

You can find the download for the vMA at http://www.vmware.com/support/developer/vima/. It can be downloaded to your management system as either a ZIP file containing the Open Virtualization Format (OVF) package for the vMA or you can use a Web URL to import the OVF package directly to your ESXi host. Use the following process to import the vMA from a URL:

  1. Start the vSphere client and connect to vCenter Server or an ESXi host.

  2. Select File > Deploy Template.

  3. Once the Deploy OVF Template wizard appears, enter the URL for the OVF download and click Next.

  4. The details of the OVF package are displayed, as shown in Figure 8.1. Click Next to continue.

    OVF template details for the vMA 4.1 download.

    Figure 8.1. OVF template details for the vMA 4.1 download.

  5. Accept the license agreement.

  6. You can optionally specify a name for the virtual appliance or accept the default of vSphere Management Assistant (vMA).

  7. Select the location for the appliance. Depending on your configuration, this may include selecting an appropriate cluster, host, and resource pool.

  8. If the destination host has multiple datastores, select a location to store the vMA file and click Next.

  9. Select a disk format for the virtual disk of the vMA.

  10. Choose the network mapping for the vMA. The vMA should have network access to the management port of your ESXi hosts if you plan to run commands directly against ESXi.

  11. Review the information for the import and click Finish.

Once the vMA has been deployed to your ESXi host, you need to perform some initial configuration steps. If you need the vMA to connect to multiple networks, you should first edit the vMA virtual machine and add the additional virtual network adapter.

To configure the vMA, follow these steps:

  1. In the vSphere client, right-click on the vMA virtual machine and select Power > Power On.

  2. Open a console session for the virtual machine.

  3. The initial configuration begins with a network configuration wizard. For each network adapter in the vMA, you can choose between using Dynamic Host Configuration Protocol (DHCP) and setting a static Internet Protocol (IP) address.

  4. Enter a primary and secondary domain name service (DNS) server to use for the vMA. The default values are populated from information obtained from a DHCP server.

  5. Select a hostname for the virtual machine.

  6. A summary of your configuration settings is displayed, as shown in Figure 8.2. Type yes and press Enter to confirm the settings.

    Reviewing the network configuration for the vMA appliance.

    Figure 8.2. Reviewing the network configuration for the vMA appliance.

  7. Next you are prompted for a password for the vi-admin account. The prompt uses the Linux passwd utility and requires a sufficiently secure password. If you enter a password that is not complex, you may receive the Bad Password error.

  8. After you have entered a password, the configuration wizard completes and a welcome screen is displayed.

Once the vMA is configured, you can log in locally at the virtual machine console by pressing Alt+F2 or remotely via Secure Shell (SSH). To change the password for the vi-admin user, enter the command passwd. To restart the network configuration wizard, run the following:

cd /opt/vmware/vma/bin
sudo ./vmware-vma-netconf.pl

Running vCLI Commands

Before you begin to look at the commands included with the vCLI, it is worthwhile to understand the connection options that are used by the vCLI commands. With all the commands, you must authenticate with either ESXi or vCenter Server. The connection options allow you to specify the authentication method and other options such as the port used for the vSphere API. Table 8.1 summarizes the connection options for the vCLI.

Table 8.1. vCLI Connection Options

Option

Description

- -config <config file with path>

VI_CONFIG=<config file with path>

This option uses the specified file for connection options

- -credstore <credential store file with path>

With this option, the credentials are stored in a file. The vSphere SDK for Perl documents how to manage the credential store file.

- -encoding <encoding> VI_ENCODING=<encoding>

This option specifies the encoding to use when run on a foreign language system. Options include ISO-8859-1 (German), Shift_JIS (Japanese), and cp936 (Simplified Chinese).

--passthroughauth

VI_PASSTHROUGHAUTH

The Microsoft Windows Security Support Provider Interface (SSPI) is used to pass authentication. This option is available only on Windows systems. If an untrusted account is used, the user is prompted for credentials.

- -passthroughpackage <package>

VI_PASSTHROUGHPACKAGE=<package>

Use this option with -passthroughauth to specify the domain-level authentication protocol that is configured for Windows. The default for SSPI is the Negotiate protocol, which means that the server and client attempt to negotiate a protocol that both can support.

- -password <password>

VI_PASSWORD=<password>

This option is used with the - -username option to log in to vCenter Server or ESXi. You should use credentials that are appropriate to either vCenter Server or ESXi and that correspond to what you have entered with the --server option. If you don’t specify this option, the system prompts you for your password.

- -portnumber <number>

VI_PORTNUMBER=<number>

This specifies the port to connect to on the vCenter Server or ESXi host if you have changed from the default of 443.

- -protocol <HTTP|HTTPS>

VI_PROTOCOL=<HTTP|HTTPS>

You can connect to the vSphere API over HTTP or HTTPS.

HTTPS is the default and the recommended option.

- -savesessionFile <file>

VI_SAVESESSIONFILE=<file>

You can save your authentication with a host to a session file.

- -server <server>

VI_SERVER=<server>

This option specifies the host to run the command against. If you connect to vCenter Server, you must also use the - -vihost option.

- -servicepath <path>

VI_SERVICEPATH=<path>

This option uses the specified service path to connect to on your ESXi host. The default is /sdk/webService.

--sessionfile <file>

VI_SESSIONFILE=<file>

This option uses a saved session file to load a previous authentication session.

--url <url>

VI_URL=<url>

With this option, you can specify the vSphere Web Services SDK URL.

- -username <username>

VI_USERNAME=<username>

This option specifies the username to use to authenticate to the host. If you are connecting to vCenter Server, you should use an account that has been granted privileges on vCenter Server. If you are connecting to an ESXi host, use an account with local privileges.

--vihost <host>

If the --server option is pointing to vCenter Server you must use the - -vihost option to specify the ESXi host to run the command against. Note that this option is not supported for all vCLI commands.

--h <host>

 

To view the connection options at a command prompt, you can use the --help option, which displays the connection options and command-specific help. Two other helpful options include –verbose, which displays additional debugging information, and –version, which shows the version information for the command and the vSphere SDK for Perl as shown in the following example:

vicfg-nics --version
vSphere SDK for Perl version: 4.1
Script 'vicfg-nics' version: 4.1

Most of the connection options in Table 8.1 deal with the method of authentication and it is worthwhile to examine how the vCLI orders the authentication methods that are available. If you’re migrating scripts from ESX to ESXi, you don’t want to embed passwords into your scripts. Rather, you want to use one of the methods that the vCLI provides, such as employing interactive logins, using a session file, or authenticating with your Windows credentials.

When you execute a vCLI command, authentication happens in the order shown in Table 8.2. This order is hard-coded and cannot be altered.

Table 8.2. vCLI Authentication Precedence

Authentication Method

Description

Command line

The vCLI uses either the --password or --sessionfile options.

Configuration file

The password is stored in a configuration file.

Environment variable

The password is specified as an environment variable.

Credential store

The command retrieves the password from a credential store file.

Windows account

Windows SSPI passes the user’s Windows credentials to the host.

Prompt for password

The user interactively enters the password, which is not echoed to the screen.

When you’re using the command-line option, you can either specify the username and password in the command or use a session file. Using the --password option in a script is not recommended as it exposes the password to anyone with access to the script. When you’re using the command-line options, you should enclose any special characters with single quotes on Linux and double quotes on Windows. You can also use the backslash () as an escape character, as shown in these examples:

Linux:

vicfg-nics --server esx01 --username 'user-1' --password 's@f#t&'
vicfg-nics --server esx01 --username user-1 --password s@f#t&

Windows:

vicfg-nics --server esx01 --username "user-1" --password 's@f#t&'

A more secure option for the command line is to use the save session script. This is an application of the vSphere SDK for Perl and is located in /usr/lib/vmware-vcli/apps/session for Linux and C:Program FilesVMwareVMware vSphere CLIPerlappssession for Windows. When you create a session file, the credentials stored in the file are valid for 30 minutes.

To create a session file, open a command prompt and go to the folder where the save_session script is stored. Run the following command to create a session file:

save_session --savesessionfile /tmp/session --server esx01 --username root

You can optionally include the --password parameter with the command, but if you don’t, the system prompts you to enter the password. The saved session file does not contain the password but rather has the following information:

#LWP-Cookies-1.0
Set-Cookie3: vmware_soap_session=""52ce644b-288d-12c9-d91f-6d6a48f832aa"";
      path="/"; domain=esx01.local; path_spec; discard; version=0

To run commands, you may now reference the session file and other connection options are ignored:

vicfg-nics --sessionfile /tmp/session -l

With configuration file authentication, a plain text file contains the connection options shown in Table 8.1. A sample file would include the following items:

VI_SERVER = esx01
VI_USERNAME = root
VI_PASSWORD = Secret
VI_ENCODING = cp936

To execute a command, you would only have to reference the configuration file for your connection options, as is shown in this example:

vicfg-nics --config '/home/vi-admin/config' -l

Environment variables present a similar way to fix connection options. On a Linux system, you can set an environment variable in your command-line session with the following command:

export VI_SERVER=esx01

You can do the same in a Windows command prompt session with this command:

set VI_SERVER=esx01

After you have set the environment variables, you can issue the vCLI commands and omit the options. In the following example, the --server option is omitted as it is already set as an environment variable:

vicfg-nics ––username root -l

With credential store authentication, the vSphere SDK for Perl is used to store and retrieve credentials from local database files. The vMA authentication component is an example of an application that uses a credential store. This is discussed further in the following section.

Tip

The credentials stored on the vMA are encrypted using standard encryption algorithms. There is a risk that a malicious user could obtain the virtual disk files for the vMA and then decrypt the passwords. To add an additional layer of security, it is possible to encrypt the filesystem in which the credentials and vMA database files are stored. That procedure is documented in this Knowledge Base article: http://kb.vmware.com/kb/1017669.

The last authentication method is to use Window SSPI and the --passthroughauth option to authenticate with vCenter Server. This option is not supported if you are connecting directly to ESXi. After you authenticate with vCenter Server, you do not have to supply credentials again for that session. You may have to set the --passthroughauthpackage option when authenticating in this manner. The default setting for this option is Negotiate, but for some systems you may have to change this setting to Kerberos.

In the following example, the option is used with the first vCLI command run and it is not required with subsequent commands:

vicfg-nics --server vcenter --vihost esx01 --passthroughauth
      --passthroughauthpackage "Kerberos" -l
vicfg-nas --server vcenter --vihost -l

Configuring vMA Components

The vMA contains two additional components over the vCLI: the vi-logger component, which captures ESXi and vCenter Server log data, and the vMA authentication component, which stores credentials to enable passthrough authentication.

Configuring vi-fastpass Authentication

The vMA authentication component allows you to authenticate with target hosts using vi-fastpass or Active Directory. When adding a server as a target, you can configure which authentication method to use. If you use vi-fastpass authentication, the credentials that you have for vCenter Server or ESXi are stored in a local credential store. If you use Active Directory authentication, no credentials are stored locally, but the user authenticates with an Active Directory server.

When using vi-fastpass with an ESXi host, two accounts with encrypted passwords are created on the ESXi host. The account vi-admin is created with administrator rights, whereas the vi-user account is created on ESXi with read-only privileges. That password information is stored locally in a credential store. To enable a number of vMA appliances to manage the same ESXi host, each vMA appliance creates the accounts in the format of vi-admin<XX> and with a unique login name, as shown in Figure 8.3.

Each vMA appliance creates a unique instance of vi-admin and vi-user on an ESXi host.

Figure 8.3. Each vMA appliance creates a unique instance of vi-admin and vi-user on an ESXi host.

If Active Directory is used to connect to the target host, the accounts are not created and no credentials are stored. It is necessary to set up the vMA to join the Active Directory (AD) domain.

Once you have configured your target hosts, you can issue the vifptarget command to start an authenticated session with the host. Subsequent vCLI commands that you run do not require the --server option or any authentication options.

Configuring Prerequisites for Active Directory Authentication

If you wish to use AD authentication, join the vMA appliance to your domain. When you configured the vMA appliance initially, you should have specified the DNS hosts for your domain and matched the domain name for the vMA appliance to your AD domain. It is also worthwhile to ensure that the time in the vMA is set to sync with your domain’s Network Time Protocol (NTP) server. You can use these steps to configure the NTP setting on your vMA appliance:

  1. Run the command sudo nano /etc/ntp.conf.

  2. Add your NTP hosts under the following section: # Use public servers from the pool.ntp.org project. Press Ctrl+X and then enter Y for Yes to save and exit.

  3. Configure the ntpd daemon to start automatically with the command sudo /sbin/chkconfig ntpd on.

  4. Restart the ntpd daemon with the command sudo /sbin/service ntpd restart.

Before you begin the process to join the vMA appliance to your AD domain, you should ensure that you can resolve vCenter Server and domain controllers by their fully qualified domain names. Then use the following steps to add the vMA appliance to your domain:

  1. Log in to the vMA appliance with vi-admin.

  2. Enter the command to join the domain as shown in the following example:

    sudo domainjoin-cli join mishchenko.net mishchenkodave.mishchenko
    
  3. When the system prompts you to do so, enter the password for the administrator account that you used for the command.

  4. Restart the vMA appliance.

After you have joined the domain, you can use the query option with domainjoin-cli to display the domain information and the leave option to remove the vMA from the domain. If you are having trouble joining the domain, ensure that the DNS settings are correct. It may also help to ensure that the time zone of the vMA appliance matches the time zone of the domain controllers. As an example, you can change the time zone to Pacific Standard Time (PST) with the following commands:

sudo rm /etc/localtime
sudo ln -s /usr/share/zoneinfo/America/Vancouver /etc/localtime

You can also begin to log in to the vMA appliance with your AD login. Then you can execute commands with the --passthroughauth option and your Windows credentials are passed through to vCenter Server and your ESXi hosts.

The second configuration item of AD authentication is to configure unattended authentication to AD targets. This process uses the Ktpass tool from Microsoft, which enables an administrator to configure a non-Windows Kerberos service as a security principal within AD. Without this setup, the vMA is not able to generate authentication tickets with AD that it uses to authenticate with vCenter Server or ESXi when it is enabled for AD integration. In the following example, the domain account is dave.mishchenko and the domain is MISHCHENKO.NET:

  1. Download the Ktpass tool from microsoft.com and install it on a Windows computer that is part of the domain.

  2. Run the Ktpass command with the following syntax:

    ktpass /out mishchenko.keytab /princ [email protected] /pass ca...
         /ptype KRB5_NT_PRINCIPAL -mapuser mishchenkodave.mishchenko
    
  3. Copy the file to the folder /home/local/MISHCHENKO/dave.mishchenko.

  4. Ensure that the owner is set to match the domain account by running the following command:

    sudo chown 'MISHCHENKOdave.mishchenko'
        /home/local/MISHCHENKO/dave.mishchenko/mishchenko.keytab
    
  5. Create the file /etc/cron.hourly/kticket-new and add the following text. Note the use of the escape character.

    #!/bin/sh
    su - MISHCHENKO\dave.mishchenko -c '/usr/kerberos/bin/kinit -k
        -t /home/local/MISHCHENKO/dave.mishchenko/mishchenko.keytab dave.mishchenko'
    

The cron job that is created renews the Kerberos ticket for the specified account each hour. You could also add the script to /etc/init.d to refresh tickets when the vMA appliance is started. If you plan to use multiple accounts to add target hosts to your vMA appliance, you need to create a keytab file for each account and update the script in step 5 to refresh the Kerberos ticket for each user account.

Adding and Managing Target Servers

In this section, you examine the steps to add the target host to your vMA appliance. The recommended method is to use AD authentication, as no passwords are stored on the vMA appliance. If the AD setup in the preceding section had not been performed, it would require adding targets with credentials that would be stored locally. In the following example, a vCenter Server and ESXi host are added as targets on the vMA appliance. The vifp command is used with the addserver option to add the hosts as targets. In both cases, the authentication policy for vifastpass is set to adauth (AD authentication).

vifp addserver vcenter.mishchenko.net --authpolicy adauth
      --username 'MISHCHENKOdave.mishchenko'
vifp addserver esx01.mishchenko.net --authpolicy adauth
      --username 'MISHCHENKOdave.mishchenko'

To query the hosts that have been added as targets, you use the listservers option:

vifp listservers --long
vcenter.mishchenko.net   vCenter adauth
esx01.mishchenko.net     ESXi    adauth

To begin using vi-fastpass, you issue the vifptarget command and set a target. No authentication is required and once you set a host with vifptarget, all subsequent commands run against that host. To switch to another target, you must issue the vifptarget command again:

vifptarget --set esx01.mishchenko.net
vicfg-nics -l
vifptarget -s vcenter.mishchenko.net
vicfg-nics --vihost esx02.mishchenko.net -l

In the case of a vMA appliance without the preceding AD configuration, you must use the fpauth authentication option as shown in the following example. Note the security warning that is displayed and the requirement to provide a password for the AD account.

vifp addserver vcenter.mishchenko.net --authpolicy fpauth
      --username 'MISHCHENKOdave.mishchenko'
[email protected]'s password:
This will store username and password in credential store which is a security risk.
Do you want to continue?(yes/no): yes
vifp addserver esx01.mishchenko.net --authpolicy fpauth
      --username 'MISHCHENKOdave.mishchenko'
[email protected]'s password:

Running a query of the targets set up on the vMA appliance, as in the following example, shows the authentication method used for these hosts, but no authentication is required as expected when setting the hosts as targets, as was the cause with the preceding AD configuration.

vifp listservers --long
vcenter.mishchenko.net    vCenter fpauth
esx01.mishchenko.net      ESXi    fpauth

vifptarget --set esx01.mishchenko.net
vicfg-nics -l
vifptarget -s vcenter.mishchenko.net
vicfg-nics --vihost esx02.mishchenko.net -l

In addition to the difference in authentication, one other difference with using vi-fastpass authentication is the setup of the accounts vi-admin and vi-user on any ESXi targets that you define. The vi-admin account is granted the Administrator role on the ESXi host, whereas the vi-user account is granted the Read-Only role. By default, the vi-user account on the vMA appliance is disabled. You can enable it by setting a password for the account. To do this, log in with the vi-admin account and run the command sudo passwd vi-user and then follow the prompts. When users log in to the vMA appliance with the vi-user account, they can only execute read-only commands against ESXi hosts set up with vi-fastpass authentication. If the account is used to run a command against an ESXi host set up with AD authentication or a vCenter Server host with any authentication mode, the user is prompted for another username and password. The vi-user account is not able to execute any commands using sudo.

The vifp command also includes the reconfigure option. This option can be used for the following purposes:

  • To change the authentication mode used with a target.

  • To change the user configured for an AD target.

  • To recover users for a vi-fastpass target. A user needs to be recovered if the vMA credential store is corrupted or if the user accounts on the ESXi host are updated without a corresponding change made on the vMA appliance.

To change the authentication policy from vi-fastpass to AD, you can issue the following command:

vifp reconfigure esx01.mishchenko.net --authpolicy adauth

To change the configured user or recover users, issue this command:

vifp reconfigure esx01.mishchenko.net

You may also have to use the removeserver option to manage hostname changes and before you delete a vMA appliance. If you change the hostname for one of your ESXi hosts, you should use the option to delete the target and then add the target again with its new hostname. You should also issue the command when you plan to delete the vMA appliance, as removing a target ESXi host deletes the vi-admin and vi-user accounts that were created when the host was first made a vi-fastpass target.

The last option for vifp to be aware of is rotatepassword. When you use the vi-fastpass authentication option, by default the passwords for the accounts created on your ESXi hosts are never changed. You can enable password changing by setting a password rotation policy. If you run the command vifp rotatepassword -- now, the passwords for vi-admin and vi-user on all your ESXi hosts are updated and the changed passwords are recorded in the local credential store. You can also append the --server option to --now to change the passwords for a specific ESXi target. The --days option is used to set the frequency of password changes, whereas --never disables password changes. If you use rotatepassword without any options, the current rotation policy is displayed.

Capturing ESXi Logs with vi-logger

With the vi-logger component, you can capture log files from vCenter Server and ESXi. Use of vi-logger is suitable for small and medium-sized environments, but for large environments, you should consider using an enterprise-scale log collection tool rather than vi-logger. From vCenter Server, you can gather the vpxd.log file, which contains logging data for the vCenter Server Windows service. For ESXi, you can capture the following log files:

  • /var/log/messages. This log file contains the VMkernel logs and warnings, host daemon messages, and other user-level daemon messages. This log file contains the same data you would find in vmkernel, vmkwarnings, and hostd log files on an ESX system.

  • /var/log/vmware/hostd.log. This is the host agent log file.

  • /var/log/vmware/vpx/vpxa.log. This is the vCenter Agent log file.

The heart of the vi-logger component is the vilogd daemon, which is responsible for log collection. The daemon is set to start automatically each time the vMA virtual machine is started. When you are logged in with the vi-admin account, you can control and check the start of the vilogd daemon. To check the status of the service, run the following command:

/sbin/service vmware-vilogd status
vmware-vilogd is running

To restart the daemon, you can issue this command:

sudo /sbin/service vmware-vilogd restart
Stopping vmware-vilogd:                   [ OK ]
Starting vmware-vilogd:                   [ OK ]

To configure hosts for log collection, you use the command vilogger. Prior to adding a host, you must configure it as a vMA target, as shown in the previous section. When you want to start capturing data, you first need to enable logging for some or all of your vMA targets. To accomplish this, you run vilogger enable, and you can include the options in Table 8.3 to customize the logging configuration. If you run vilogger enable with no options, all your vMA targets are enabled for logging with the default values for the options in Table 8.3.

Table 8.3. vilogger enable Command Options

Option

Description

server

This specifies the hostname or IP address for the vMA target. If this option is omitted, all vMA targets are added.

logname

You can specify a log file to capture. The default value is to enable all log files.

collectionperiod

This option specifies how often a log file should be collected. The default value is 10 seconds and you can use a value between 10 and 3600.

maxfilesize

With this option, you set the maximum size for log files before rollover. The default value is 5MB and you can set the value between 1 and 1024.

numrotation

This option sets the number of log files to keep before the oldest is deleted. The default is 5 and you can configure this option with a value between 1 and 1024.

You can use any combination of options to customize the logging level for each host. In the following example, the first command gathers all log files on an ESXi host and collects data every 60 seconds. The second command collects the vpxd.log file from vCenter Server and retains 100MB worth of logged data, using 10 log files.

vilogger enable --server esx01.mishchenko.net --collectionperiod 60

Target Server: esx01.mishchenko.net
hostd       ... Enabled
messages    ... Enabled
vpxa        ... Enabled

vilogger enable --server vcenter.mishchenko.net --numrotation 10 --maxfilesize 10

Target Server:  vcenter.mishchenko.net
vpxd        ... Enabled

To review the logs being collected by the vilogd daemon, you can issue the command vilogger list. You can optionally include --server or --logname to filter the output. The output of vilogger list is shown in Figure 8.4.

Displaying the vilogger configuration with vilogger list.

Figure 8.4. Displaying the vilogger configuration with vilogger list.

Tip

As mentioned in an earlier chapter, when ESXi logs data, the time stamps are in the Coordinated Universal Time (UTC) time zone. You can change the vMA to have the same time zone with the following commands:

sudo rm /etc/localtime
sudo ln -s /usr/share/zoneinfo/UTC /etc/localtime
sudo reboot

To update log collection for a vMA target, you can use vilogger updatepolicy. This command uses the options shown in Table 8.3. To update the logging configuration for the ESXi host used in the preceding example, you would issue the following command:

vilogger updatepolicy --server esx01.mischenko.net --collectionperiod 30

With this command, all logs being gathered for the ESXi host would now be collected every 30 seconds. If you need to disable logging, you can use vilogger disable. This command takes the options of --server, --logname, and --force. The --force option should be used when the vMA target is unreachable; otherwise, the vilogger disable command fails. In the first example, logging of the message’s log file for an ESXi host is disabled; in the second example, all logging for an ESXi host is disabled; and in the last example, all logging on the vMA appliance is disabled.

vilogger disable --server esx01.mishchenko.net --logname messages
vilogger disable --server esx01.mishchenko.net
vilogger disable

Managing vSphere with the vCLI

The vCLI includes many commands to make the transition from managing your ESX hosts at the console to managing ESXi with the vCLI an easy road. Version 4.1 of the vCLI includes new commands to configure AD integration, configure Internet Protocol Security (IPSec), and to manage the state of your hosts. Use of some of the vCLI commands has already been discussed in other chapters, so we won’t repeat their discussion here. Rather, this section highlights some of the commands that are available and discusses the new vCLI features for ESXi 4.1. For a more complete reference to the vCLI, you can consult the vSphere Command-Line Interface Manual and the vSphere Command-Line Interface Reference. Both can be found at the following URL: http://www.vmware.com/support/developer/vcli/.

A list of the vCLI commands can be found in Table 8.4. For the most part, these commands may be run against ESX(i) 3.5, ESX(i) 4.x, and vCenter Server. The commands that must be executed directly against an ESXi host were noted earlier in this chapter. If you are starting to migrate from ESX 3.5 to ESXi 4.1, you can begin to use the vCLI on your existing ESX hosts and start to convert your scripts to execute with the vCLI instead of the Service Console. If you review the vCLI commands in the vCLI bin folder, you can see that many of the commands exist both with an esxcfg and a vicfg prefix. The esxcfg commands are included to provide backward compatibility for the scripts you may have. On Linux systems, the esxcfg commands exist as symbolic links to the corresponding vicfg commands. If you are developing new scripts for the vCLI, it is recommended to use the vicfg commands, as the esxcfg commands may not be included in the future. New commands added to the vCLI such as vicfg-hostops do not include an esxcfg equivalent.

Table 8.4. vCLI Command Summary

Option

Description

esxcli

Provides a command-line interface to access components called namespaces. Some of the namespaces allow management of elements such as storage multipathing, software iSCSI, and virtual machines.

resxtop

Monitors ESXi hosts in real-time or Batch Mode.

svmotion

Migrates a virtual machine’s configuration file and disks between datastores that the virtual machine is running.

vicfg-advcfg

Configures advanced options, including enabling and disable Common Information Model (CIM) providers.

vicfg-authconfig

Enables the configuration of an ESXi host for AD integration.

vicfg-cfgbackup

Backs up and restores the system configuration files for an ESXi host.

vicfg-dns

Configures the DNS settings for an ESXi host.

vicfg-dumppart

Manages the diagnostic partitions.

vicfg-hostops

Performs host operations, including rebooting hosts and placing a host in Maintenance Mode.

vicfg-ipsec

Secures IP communication by enabling IPsec for IPv6.

vicfg-iscsi

Configures iSCSI storage.

vicfg-module

Manages VMkernel modules.

vicfg-mpath

Configures storage arrays.

vicfg-mpath35

Configures storage arrays for ESX(i) 3.5 hosts.

vicfg-nas

Configures network attached storage (NAS) for use as datastores.

vicfg-nics

Manages your ESXi host’s physical network interface cards (NICs).

vicfg-ntp

Configures NTP settings for your host.

vicfg-rescan

Rescans your storage configuration for changes and new storage.

vicfg-route

Changes the routes used for the VMkernel on ESXi.

vicfg-scsidevs

Lists available logical unit numbers (LUNs).

vicfg-snmp

Configures SNMP on your ESXi host.

vicfg-syslog

Configures the syslog server and port to which your ESXi host forwards log files.

vicfg-user

Manages users and groups defined locally on ESXi.

vicfg-vmknic

Configures the VMkernel network interfaces.

vicfg-volume

Manages duplicate Virtual Machine File System (VMFS) volumes, including resignaturing, mounting, and unmounting.

vicfg-vswitch

Manages virtual switches (vSwitches) on the ESXi host.

vifs

Performs filesystem operations such as uploading files to a datastore.

vihostupdate

Updates ESXi 4.x hosts.

vihostupdate35

Updates ESXi 3.5 hosts.

vmkfstools

Manages virtual disks, datastores, and storage devices.

vmware-cmd

Manages virtual machines, including starting and stopping them.

Managing ESXi Hosts

The host-related commands can perform a number of management and configuration tasks on your ESXi hosts. You have already seen examples of a number of these commands used in previous chapters, such as vicfg-authconfig for enabling AD integration, vicfg-ipsec for configuring IPsec, and vicfg-ntp for enabling NTP synchronization. In the following section, you learn about the other host-related vCLI commands.

One of the new vCLI commands in vSphere 4.1 is vicfg-hostops. To shut down a host, you can issue the following command:

vicfg-hostops --operation shutdown --force.

With the --force option, the command shuts down all running virtual machines and then the host. You can omit this option if you’ve put the host into Maintenance Mode. With this command, you can also use the --cluster or --datacenter options to shut down entire clusters or datacenters as required.

Note

Throughout this section and the following sections, connection options are not displayed with the commands. If you are not using vi-fastpass authentication or another method to specify the connection options discussed earlier, you need to add those options.

You can also use the reboot option, which works in the same manner as shutdown and accepts the same options. Prior to issuing a reboot or shutdown command, a host should be placed in Maintenance Mode. For a host that is a member of a Distributed Resource Scheduler (DRS) cluster, the virtual machines running on the host migrate to other hosts before the server can enter Maintenance Mode. If the host is not a member of a DRS cluster, vicfg-hostops suspends any running virtual machines. A host remains in Maintenance Mode until you take it out of Maintenance Mode, and no virtual machines can be started on a host in Maintenance Mode. Run the following command to place a host into Maintenance Mode:

vicfg-hostops --operation enter

You can also use the --cluster or --datacenter options with this operation. To take a host out of Maintenance Mode, you can substitute the option exit. When you put a host in Maintenance Mode, you can get the status of that operation with the info option. This option also displays information about the host’s central processing unit (CPU), memory, whether vMotion is enabled, and the last boot time. An example of the output for the info option follows:

vicfg-hostops --operation info

Host Name           : esx01.mishchenko.net
Manufacturer        : Supermicro
Model               : X8DTL
Processor Type      : Intel(R) Xeon(R) CPU E5520 @ 2.27GHz
CPU Cores           : 4 CPUs x 2266 GHz
Memory Capacity     : 8182.8359375 MB
vMotion Enabled     : yes
In Maintenance Mode : yes
Last Boot Time      : 2010-07-27T06:10:48.791755Z

Note

One of the sample scripts included with the vSphere SDK for Perl is a utility called hostops. In addition to providing the operations performed by vicfg-hostops, this utility includes the following operations: add_standalone, disconnect, addhost, reconnect, removehost, moveintofolder, and moveintocluster. You can find more information about this utility in this document: http://www.vmware.com/support/developer/viperltoolkit/viperl41/doc/hostops.html.

Each of your ESXi hosts should be configured with a dump partition. The command vicfgdumppart is used to display the configuration of the dump partition and to make changes to it. The dump partition is used to store core dumps should your host fail and display a purple screen. You can modify the dump partition to be located on a Fibre Channel or iSCSI LUN, but the iSCSI LUN should be accessible via a hardware iSCSI adapter.

To display the current configuration, issue the following command:

vicfg-dumppart --get-active

To display the potential targets, you can use the --find option. The active dump partition is shown as well as all potential partitions. The output may display partitions accessible via the ESXi software iSCSI adapter, but these should not be used for the dump partition. To change the dump partition, you first run vicfg-dumppart with the --deactivate option. Then use the --set option and specify one of the available partitions to set and activate the new dump partition.

From time to time, you may find that you have to set advanced configuration options on your ESXi host. This can be accomplished with the vSphere client, as shown in Figure 8.5. You may be instructed by VMware support to make such a change or you may be following a Knowledge Base article.

Adjusting advanced configuration settings with the vSphere client.

Figure 8.5. Adjusting advanced configuration settings with the vSphere client.

These configuration changes can also be made with the command vicfg-advcfg. The following commands are used to increase the number of Network File System (NFS) mounts that an ESXi host can support:

vicfg-advcfg -s 32 NFS.MaxVolumes
Value of MaxVolumes is 32

vicfg-advcfg -s 120 Net.TcpipHeapMax
Value of TcpipHeapMax is 120

Tip

Another useful sample script in the vSphere SDK for Perl is mcli, which is found in /opt/vmware/vima/samples/perl. This script can be used to execute a command against a number of hosts. First generate a text file containing the hostnames of your ESXi scripts. Then run the script with the following syntax to run the vicfg-advcfg command against all the hosts listed in the text file.

mcli <file containing ESXi server list> vicfg-advcfg -s 32 NFS.MaxVolumes

The vicfg-module command is used to set and retrieve VMkernel module options. The --list and --query options display the modules that the VMkernel has loaded. You can change options for a module with the --set-option option. The following example changes the queue depth for all Emulex Fibre Channel adapters using the specified module:

esxcfg-module --set-option 'lpfc_lun_queue_depth=20' lpfc820.o

After you have set an option, you can use the following command to query the module to verify the change:

esxcfg-module --get-option lpfc820.o

The final command for managing your host that this section discusses is vicfg-user. This command is used to manage accounts and groups that are locally defined on your ESXi host. With this command, you can assign users and groups to a role, but you cannot create or manage roles with it. Table 8.5 lists the command’s options. The command is always issued with the following format:

vifcg-user --entity <user | group> --operation <add | modify | delete | list>

To create a user, you can use the following command:

vicfg-user --entity user --operation add --login user1 --newpassword Secret45

Table 8.5. vicfg-user Command Options

Option

Description

--entity <group|user>

The object to perform the operation on. This is either user or group.

--operation

The operation to perform. This can include add, delete, list, or modify.

--addgroup <group_list>

Comma-separated list of groups to add a user to.

--adduser <user_list>

Comma-separated list of users to add to a group.

--group <name>

The name of the group.

--groupid <group_id>

The group ID for the group.

--login <login_id>

Login ID of the user.

--newpassword <p_wd>

Password for the target user.

--newuserid <UUID>

New UUID for the target user.

--newusername <name>

New username for the target user.

--removegroup <group_list>

Comma-separated list of groups to remove a user from.

--removeuser <user_list>

Comma-separated list of users to remove from a group.

--role <admin|read-only|no-access>

Role to assign user to. The valid options are admin, read-only, and no-access.

The command does not include the --role option, so this new login does not have access to the ESXi host. To verify that the user was created, you can change the operation to list to view all users defined on the host:

vicfg-user --entity user --operation list

To change the role for an existing user, change the operation to modify, as the following example shows:

vicfg-user --entity user --operation modify --login user1 --role admin

The vicfg-user command script is coded to accept only admin, read-only, and no-access as valid roles even if you have defined other roles on the host. If you are interested in learning more about scripting with the vSphere SDK for Perl, you can start by modifying an existing script such as vicfg-user to meet your needs.

To manage groups with vicfg-user, you change the --entity option to group. If you require a number of local users on your ESXi hosts with the same permissions, it is easier to create a group, assign permissions to the group, and then to add users to the group. To create a new group and assign a role to it, issue the following command. You can optionally add the --groupid parameter to assign a group ID to the new group.

vicfg-user --entity group --operation add --group ESXiAdmins --role admin

To add a user to that group, you can issue the following command:

vicfg-user --entity group --operation modify --group ESXiAdmins --adduser admin1

To add a number of users to the group in one command, you list the users separated by a comma:

vicfg-user --entity group --operation modify --group ESXiAdmins
      --adduser admin1, admin2, admin3

Although such use is not documented as being officially supported, you can use vicfg-user to manage AD users if the host has been enabled for AD integration. You cannot create an AD user or group on your ESXi, but you can assign a role to the account or group.

vicfg-user --entity user --operation modify -login 'MISHCHENKOdave.mishchenko'
      --role admin
Updated user MISHCHENKOdave.mishchenko successfully.
Assigned the role admin
vicfg-user --entity user --operation delete -login 'MISHCHENKOdave.mishchenko'
Removed the user MISHCHENKOdave.mishchenko successfully.

vicfg-user --entity group --operation modify --group 'MISHCHENKODomain Admins'
      --role admin
Assigned the role admin
Vicfg-user --entity group --operation delete --group 'MISHCHENKOdomain^admins'
Deleted MISHCHENKOdomain^admins successfully.

Note that although the commands to add an AD user or group are not case-sensitive for the username or group name, it is case-sensitive when the commands are deleting the user or group. When adding a user or group with a space in the name, ESXi replaces the space with the ^ character. When you delete the user or group, you must include this as shown in the removal of the domain admins group in the preceding example.

Managing Virtual Machines

The vCLI includes a version of vmware-cmd, svmotion, which allows you to migrate virtual machines, and the esxcli command has been improved to allow the forcible termination of virtual machines. The vmware-cmd enables the following virtual machine functions:

  • Start, stop, and reset virtual machines

  • List and register virtual machines

  • Manage virtual machine snapshots

  • Retrieve virtual machine attributes

  • Connect and disconnect virtual devices

  • Retrieve user input

When using vmware-cmd, you follow this syntax for entering commands:

vmware-cmd <virtual machine config file> <operation> <operation options>

To view a list of virtual machines registered on your ESXi host, you run the following command. The output lists the full path to the virtual machines configuration file, including the datastore UUID rather than the datastores logical name.

vmware-cmd -l
/vmfs/volumes/4a7cf921-017eb919-bb32-000423e540c6/SQL04/SQL04.vmx

When entering vmware-cmd commands that require the virtual machine’s configuration file, you can enter the full path as shown in the preceding example. Alternatively, you can use the data-store logical name in either of the following formats. If you are using the first method shown, you need to enclose the path in quotes appropriate to the OS that you are running the vCLI on.

[datastore1] SQL04/SQL04.vmx
/vmfs/volumes/datastore1/SQL04/SQL04.vmx

To register a virtual machine, you can use the -s option, as shown in this example:

vmware-cmd -s register vmfs/volumes/datastore1/SQL04/SQL04.vmx

For vmware-cmd commands, a 1 is returned for a successful operation and a 0 for a failure.

You can use vmware-cmd to obtain information about the virtual machine and the host that it is running on. Table 8.6 summarizes the operations that are available.

Table 8.6. vmware-cmd Attribute Operations

Operation

Description

getuptime

This displays virtual machine uptime is seconds

getproductinfo product

This lists the VMware product that the virtual machine is running on.

getproductinfo platform

This lists the host platform such as Linux or Windows for VMware Workstation or vmnix-x86 for ESXi.

getproductinfo build, majorversion, minorversion

These options return build information about the platform hosting the virtual machine.

getstate

This returns information about the state of the machine, which can be on, off, suspended, or unknown.

gettoolslastactive

This returns the state of VMware Tools and the time interval since the last VMware Tool heartbeat. The values for the statistics of VMware Tools are 0 (VMware Tools is not installed or running), 1 (the guest OS is responding okay), 5 (there is an intermittent heartbeat, which could indicate an issue), and 100 (there is no heartbeat, which may indicate that the guest OS has stopped responding).

To start the virtual machine, you can use the following command. To stop the virtual machine, you change the operation to stop, but you also must specify an operation option of soft or hard. For the soft option, ESXi attempts to perform a clean shutdown of the guest OS via VMware Tools. With the hard option, ESXi simply powers down the virtual machine. The other power operations are suspend and reset.

vmware-cmd /vmfs/volumes/datastore1/SQL04/SQL04.vmx start

In some cases, you may find that you cannot power down a virtual machine or reset it. On ESX, you may have followed a process of accessing the Service Console, using the ps command to find the process ID for the virtual machine and then issuing a kill command on that process ID. With ESXi and the vCLI, you can use esxcli to accomplish the same process. esxcli is a new interface for vSphere that provides modular access to various components called namespaces. esxcli accesses an unpublished API to perform high-level configuration, such as iSCSI configuration and storage multipathing, and management of various components, such as core storage commands.

To use esxcli to kill an unresponsive virtual machine, you first need to determine the World ID. Run the following command to return a list of running virtual machines on the host:

esxcli vms vm list
SQL04
  World ID: 9577
  Process ID: 0
  VMX Cartel ID: 9576
  UUID: 56 4d 2e 83 2f 38 ff 7f-ff f8 62 58 03 86 2b a0
  Display Name: SQL04
  Config File: /vmfs/volumes/4a7cf921-017eb919-bb32-0423e540c6/SQL04/SQL04.vmx

After you have the World ID, you can issue the kill command:

esxcli --server esx01 vms vm kill --type hard --world-id 9577
true

The kill command requires the option --type to specify the nature of the kill operation to perform. The following three options are available and should be executed in sequential order:

  • soft. This option attempts to shut the virtual machine down cleanly similar to using kill or kill -SIGTERM with ESX.

  • hard. This stops the VMX process immediately like kill -9 or kill -SIGKILL.

  • force. This option should be used if the other two options are not able to shut down the virtual machine.

The svmotion command allows you to move a virtual machine’s configuration file and optionally its virtual disks to another datastore while the virtual machine is running. You can choose a single location for the configuration file and virtual disks or choose separate locations for each. You can’t change the host that the virtual machine is running on with svmotion.

The svmotion command can be run in one of two modes. In Noninteractive Mode, you specify the new location for the configuration file and optionally new locations for one or more of the virtual disks:

svmotion --datacenter=<datacenter name>
   --vm <virtual machine configuration datastore path>:<new datastore>
   [--disks <virtual disk datastore path>:<new datastore>,
   <virtual disk datastore path>:<new datastore>]

With Interactive Mode, you add the --interactive option, in which case all other options are ignored. In this mode, the script prompts you for each required parameter. The parameters that you enter are validated as you enter them; because of this, you cannot, for example, enter a datastore name that does not exist. This option can be useful for troubleshooting if you are having problems with Noninteractive Mode. For either mode, you should ensure that you enclose parameters in quotes if they contain special characters.

Managing Host Networking

With the vCLI networking commands, you can manage the configuration of your host’s networking services. The vCLI includes the following four commands for networking: vicfgnics, vicfg-vswitch, vicfg-vmknic, and vicfg-route.

To manage the physical NICs in your host, you use the command vicfg-nics. The --list option provides a list of the NIC ports that are visible to your host, as shown in Figure 8.6. You may need to obtain this information before you can begin to create vSwitches.

A list of physical NIC ports generated by vicfg-nics.

Figure 8.6. A list of physical NIC ports generated by vicfg-nics.

Should you need to configure the speed or duplex settings for a NIC, you can use the --speed and --duplex options. To set the speed and duplex for the vmnic0 of the host, you would issue the following command:

vicfg-nics --duplex full --speed 1000 vmnic0

A NIC can be set to auto negotiation with this command:

vicfg-nics --auto vmnic0

The vicfg-vswitch command is used to manage both standard vSwitch and Distributed Virtual Switches (dvSwitch). With dvSwitches you must create a dvSwitch and then add hosts to it with the vSphere client when connected to vCenter Server. You can then manage ports and properties with vicfg-vswitch.

To create a new vSwitch, you can issue the following command. No output is displayed unless there is an error.

vicfg-vswitch --add vSwitch1

To create a port group on that vSwitch, you issue the following command:

vicfg-vswitch --add-pg iSCSI1 vSwitch1

Tip

If you’re scripting creation of vSwitches and port groups, you can check for the existence of either before issuing the command to create them. The check returns a value of 1 if the object exists and 0 if it does not.

vicfg-vswitch --check vSwitch1
1
vicfg-vswitch --check-pg PortGroup1 vSwitch1
0

To link a vSwitch to a physical network port, you can use the command that follows. You can also link a NIC port to a specific port group.

vicfg-vswitch --link vmnic2 vSwitch1
Updated uplinks: vmnic2

Should you require the setup of virtual local area networks (VLANs) on your port groups, use the --vlan option. You can configure a specific VLAN, use 0 to disable the VLAN for a port group, or use 4095 to allow VLAN tags set by the guest OS to pass through the vSwitch unchanged. The following example sets the VLAN to 100 for the port group created earlier:

vicfg-vswitch --vlan 100 -pg PortGroup1 vSwitch1

Once you have configured your vSwitch, you can review the settings with the --list option. If you want to enable jumbo frames, you may also change the maximum transmission unit (MTU) for the vSwitch with the --mtu option. If you’re using Cisco switches, you can enable the Cisco Discovery Procotol with --set-cdp.

To configure VMkernel networking, you use the vicfg-vmknic command. With ESXi, you have no Service Console ports, but rather you create a VMkernel port for management traffic, vMotion traffic, and IP storage. If you’re configuring iSCSI storage, you can first create a VMkernel port and then bind it for iSCSI usage with esxcli, as you can see in the next section, “Managing Host Storage.”

To add a new VMkernel port, you supply an IP address, subnet mask, and name, as in the following example. The name should be an existing port group that you’ve created with vicfgvswitch.

vicfg-vmknic --add --ip 192.168.1.105 -n 255.255.255.0 iSCSI1
Added the VMkernel NIC successfully

To change the IP address for a VMkernel port, you can issue the following command. You can either specify an IP address or DHCP if you plan to use that.

vicfg-vmknic --ip 192.168.1.110 iSCSI1

Some of the other options for the command include --enable-vmotion, --mtu to set the MTU, and --tso to disable Transmission Control Protocol (TCP) Segmentation Offload (TSO) for the VMkernel port. If you plan to use IPv6 with your VMkernel networking, you must first enable IPv6 on the VMkernel port. To enable IPv6, you can issue the following command sequence:

vicfg-vmknic --enable-ipv6 true iSCSI1
Please reboot the system now for the change to take effect.
vicfg-hostops --operation enter
Host esx10.mishchenko.net entered into maintenance mode successfully.
vicfg-hostops --operation reboot
Host esx10.mishchenko.net rebooted successfully.

After the host has rebooted, you can set an IPv6 address on a VMkernel port using the --ip option used earlier for an IPv4 address. The valid options for setting an IPv6 address are to use a static IPv6 address, DHCPv6 for a DHCP IPv6 address, and AUTOCONF to obtain an IPv6 address via router advertisement. Don’t forget to take the host out of Maintenance Mode.

To disable IPv6 on the host, you first remove the IPv6 address and then use the --enable-ipv6 option to disable it:

vicfg-vmknic --unset-ip 2001:10:20:253::20/64
vicfg-vmknic --enable-ipv6 false iSCSI1

To manage the VMkernel gateway or routing, you can use vicfg-route. If the command is run without any options, the IPv4 default gateway is shown. Use the --family v6 option to configure or display the IPv6 gateway. To set the default VMkernel gateways for IPv4 and IPv6, run the following commands:

vicfg-route --add default 192.168.1.1
vicfg-route --family v6 --add default 2001:10:20:253::1

To change the default gateway, you must first delete the existing gateway and then add the new one. Use the following command to delete the default IPv6 gateway:

vicfg-route --family v6 --delete default 2001:10:20:253::1
WARNING! Removing the default route for system!
Removing the default route may result in lost network connectivity
Are you sure you wish to proceed? (y/n) y

To add routes to your ESXi host, you can use the following commands:

vicfg-route --add 192.168.2.0/24 192.168.1.2
vicfg-route --family v6 --add 2000:10:20:254::/64 2001:10:20:253::2

One of the new namespaces added to esxcli for vSphere 4.1 is network. This namespace allows you to list information about the current IP connections and the active Address Resolution Protocol (ARP) table for the host. The first execution of esxcli network that follows uses the connection application with the list command. This displays the current connections for the host in numeric format and is the equivalent to running netstat -tuwln at the console of an ESX host. It is possible to filter the output by using the -t | --type option and specifying a type of ip, tcp, udp, or all. In the second instance of esxcli network, the neighbor application is run with the show command. This displays the active ARP table entries. You can use the option -v | --version with the switches of 4, 6, or all to filter IPv4 and IPv6 addresses.

esxcli network connection list

Proto   Recv-Q   Send-Q Local Address       Foreign Address     State        World ID
------- ------   --------- ----------       ---------------     -----------  ---------
tcp     0        492    127.0.0.1:51002     127.0.0.1:8307      ESTABLISHED  899921
tcp     0        0      192.168.1.30:443    192.168.1.27:35438  ESTABLISHED  902512
tcp     0        0      127.0.0.1:5988      127.0.0.1:63363     FIN_WAIT_2   0
tcp     0        0      127.0.0.1:63363     127.0.0.1:5988      CLOSE_WAIT   899919
tcp     0        0      127.0.0.1:5988      127.0.0.1:52581     TIME_WAIT    0
tcp     0        0      192.168.1.30:49154  192.168.1.5:389     TIME_WAIT    0
tcp     0        0      192.168.1.30:443    192.168.1.225:60225 ESTABLISHED  902510
tcp     0        0      192.168.1.30:902    192.168.1.225:60211 ESTABLISHED  0
tcp     0        0      192.168.1.30:894    192.168.1.100:2049  ESTABLISHED  0
tcp     0        0      192.168.1.30:61602  192.168.1.105:3260  ESTABLISHED  4967

esxcli network neighbor list

Neighbor                  Mac Address        vmknic  Expiry(sec)   State
--------                  -----------        ------  -----------   ------
192.168.1.1               00:04:5a:fb:a9:2d  vmk0    1169
192.168.1.5               00:10:a4:f2:30:a5  vmk0    1195
192.168.1.100             00:0e:0c:c2:ce:fb  vmk0    1014
192.168.1.105             00:0c:29:35:9e:49  vmk0    1118
192.168.1.225             00:23:54:06:f3:a6  vmk0    1178
fe80::230:48ff:fedb:6888  00:30:48:db:68:88  vmk0    0             Reachable

Managing Host Storage

The vCLI contains a number of commands to manage storage devices, datastores, and files. These can be used to manage local, Fibre Channel, iSCSI, and NFS storage for your hosts.

With the support of vMotion, DRS, and High Availability on NFS volumes, NFS is increasingly becoming the choice of storage for ESXi hosts. ESXi supports NFS version 3 over TCP/IP. After you have your networking set up for access to your NFS server, you can use esxcfg-nas to configure the NFS share as a datastore. The following command is used to list any existing NFS datastores:

vicfg-nas --list
NFS1 is /NFS1 from 192.168.1.100 mounted

To add another datastore, you use the --add option as shown in this example and add the NFS server hostname or IP address, the share name, and the datastore name to use. You can add the -y option to make the mount read-only, which would be appropriate for a datastore storing ISO images:

vicfg-nas --add -y --nasserver 192.168.1.100 --share /NFS2 NFS2

The following steps use vicfg-iscsi to enable and configure the ESXi software iSCSI initiator to create a new datastore on an iSCSI server. One of the significant iSCSI improvements in vSphere is iSCSI multipathing. With ESX 3.5, the iSCSI initiator can establish only a single TCP connection to each iSCSI target. Thus iSCSI traffic is limited to a single NIC port within a vSwitch, even though the vSwitch may be linked to multiple NICs. If your environment has required greater throughput, you may have configured your iSCSI storage with multiple iSCSI targets and your hosts with a number of VMkernel ports to be able to initiate multiple iSCSI sessions to your iSCSI storage. The default behavior with vSphere is the same as with ESX 3.5 to allow for a simple upgrade from ESX 3.5. But you can enable multipathing with esxcli to enable multiple connections to the same iSCSI target.

To begin, vicfg-iscsi is used to enable the software iSCSI initiator on ESXi. The subsequent commands verify that the initiator is enabled and determine the Host Bus Adapter (HBA) ID.

vicfg-iscsi --swiscsi --enable
Enabling software iSCSI...

vicfg-iscsi --swiscsi --list
Software iSCSI is enabled.

vicfg-iscsi --adapter --list
vmhba33         iSCSI Software Adapter

You can optionally set an alias for an iSCSI HBA. The iSCSI name generated for the iSCSI HBA is similar to iqn.1998-01.com.vmware:esx10-627fb181. An alias provides a more manageable name for the device and can be changed with the following command. You can also change the iSCSI name, but you must ensure that you assign a name that is unique within your organization.

vicfg-iscsi --swiscsi --iscsiname --alias ESX10_vmhba33 vmhba33

After you have enabled the iSCSI software initiator, you can add a discovery target. The target can be dynamic or static. With dynamic discovery, all storage targets associated with a hostname or IP address are discovered. With static discovery, you specify the hostname or IP address and the iSCSI name of the storage target. The following example adds an iSCSI target with dynamic discovery:

vicfg-iscsi --server esx10 --username root --password '' --swiscsi --discovery
      --add --ip 192.168.2.105 vmhba33
Adding discovery address 192.168.2.105:3260 ...
A rescan of the host is recommended for this configuration change.

To secure access to your iSCSI targets, you may employ the Challenge-Handshake Authentication Protocol (CHAP). With CHAP authentication, both the ESXi host and iSCSI target share a common username and password. During iSCSI login, the ESXi host authenticates with the iSCSI target. You can also enable mutual authentication in which the iSCSI target is also required to authenticate with the ESXi host. When configuring CHAP authentication, one of the levels shown in Table 8.7 is required.

Table 8.7. Supported Levels for iSCSI CHAP

Level

Description

chapProhibited

The host does not use CHAP authentication. You can use this option to disable authentication if it has been enabled.

chapDiscouraged

The host uses a non-CHAP connection but allows CHAP if required by the iSCSI target.

chapPreferred

The host attempts a CHAP connection but fails to achieve a non-CHAP connection if the iSCSI target does not support CHAP.

chapRequired

The host requires successful CHAP authentication.

To enable authentication with an iSCSI target, you can issue the following command. In this case, CHAP is required and the ESXi host authenticates with the iSCSI target at 192.168.2.105 with a username of user1 and a password of pass5. This example sets CHAP authentication for a specific iSCSI target. If the -i option were excluded, CHAP authentication would be enabled for all iSCSI targets. This mimics the behavior of the vSphere client, with which you can enable CHAP settings on both the HBA and target levels.

vicfg-iscsi --authentication -c chapRequired -m CHAP -u user1 -w pass5
     -i 192.168.2.105 vmhba33

If you need to enable mutual CHAP, you should first enable CHAP before running the command that follows. The username and password used for mutual authentication do not need to match the values that you used to set up CHAP authentication. However, the CHAP level must match. Note that the command syntax is nearly identical, but it adds the -b option for mutual authentication.

vicfg-iscsi --authentication -c chapRequired -m CHAP -b -u user3 -w pass4
      -i 192.168.2.105 vmhba33

To review the authentication settings for the HBA you have configured, you can issue this command:

vicfg-iscsi --authentication --list vmhba33

Tip

If you configure Advanced Settings for your iSCSI connections using the vSphere client as shown in Figure 8.7, you can also configure those with vicfg-iscsi using the -W option.

iSCSI Advanced Settings in the vSphere client may also be set using vicfg-iscsi.

Figure 8.7. iSCSI Advanced Settings in the vSphere client may also be set using vicfg-iscsi.

After you have completed the setup for your iSCSI connected storage, you can issue the following command to rescan for new LUNs. vicfg-rescan should be run each time you make a storage configuration change.

vicfg-rescan vmhba33
Scan operation succeeded.

You can then use vicfg-scsidevs to view the storage LUNs that have been discovered. With this command, you can display data such as the UUID, device type, display name, and multi-pathing plug-in. With that information, you can utilize vmkfstools to format the LUN as a VMFS datastore or to create a raw device mapping. With vmkfstools, you can manage data-stores, including extending datastores and virtual disks in the same manner in which you would use vmkfstools at the Service Console.

With the preceding setup, the iSCSI initiator makes a single connection to the iSCSI target. In the following example, vSwitch1 has been created for iSCSI storage and it is linked to vmnic2 and vmnic3. As the following output from resxtop shows the network traffic for the iSCSI target is passing through vmnic2 while vmnic3 is idle. resxtop is discussed later in the chapter.

 PORT-ID         USED-BY TEAM-PNIC   DNAME       PKTTX/s   MbTX/s
16777217      Management       n/a   vSwitch0       0.00     0.00
16777218          vmnic0         -   vSwitch0    1089.87     0.74
16777219            vmk0    vmnic0   vSwitch0    1089.87     0.74
33554433      Management       n/a   vSwitch1       0.00     0.00
33554434          vmnic2         -   vSwitch1     522.65   125.30
33554435          vmnic3         -   vSwitch1       0.00     0.00
33554441            vmk1    vmnic2   vSwitch1     522.65   125.30
33554442            vmk2    vmnic3   vSwitch1       0.00     0.00

With esxcli from the vCLI, you can enable iSCSI multipathing. As you have seen previously, esxcli can be used to kill a virtual machine, but it can also be used to configure and manage a wide range of storage options, including iSCSI sessions and storage path policies. It is worthwhile to review the vCLI guides provided by VMware to gain a full understanding of the power of the vCLI utility.

Before enabling multipathing, you should configure your vSwitch so that each VMkernel port is set to be active on only one of the physical NIC links. Figure 8.8 shows that the iSCSI1 VMkernel port has been set to be active on vmnic2 and not to use vmnic3. The iSCSI2 VMkernel port is set in a similar manner to be active on vmnic3 and not to use vmnic2.

Preparing your vSwitch for iSCSI multipathing.

Figure 8.8. Preparing your vSwitch for iSCSI multipathing.

To configure multipathing, you must first determine the VMkernel interface names for the iSCSI port groups that have been created on the vSwitch. The command to display those interface names follows. Those interface names are then used with esxcli to add the VMkernel port to the software iSCSI HBA.

vicfg-vmknic --list
Interface  Port Group/DVPort     IP Family   IP Address               Netmask
vmk0       Management Network    IPv4        192.168.1.40             255.255.255.0
vmk0       Management Network    IPv6        fe80::20c:29ff:fe3f:dab0 64
vmk1       iSCSI1                IPv4        192.168.2.115            255.255.255.0
vmk1       iSCSI1                IPv6        fe80::250:56ff:fe72:d55e 64
vmk2       iSCSI2                IPv4        192.168.2.116            255.255.255.0
vmk2       iSCSI2                IPv6        fe80::250:56ff:fe73:834  64

esxcli swiscsi nic add -n vmk1 -d vmhba33
esxcli swiscsi nic add -n vmk2 -d vmhba33

To verify your setup, you can use the list option to display the VMkernel ports that have been bound to the HBA. If the settings are correct, you can issue the rescan command to discover the new paths to your iSCSI target:

esxcli swiscsi nic list -d vmhba33
vicfg-rescan vmhba33
Scan operation succeeded.

Managing Files

To manage files on your ESXi host, the vCLI includes the command vifs. If you’re copying or cloning virtual disks on your datastores, vmkfstools is still the command to use. However, with vifs you can create folders, manage all file types, and copy files between your ESXi host and your management computer. This is one of the significant differences you’ll find with using the vCLI to manage your host. With the service console on ESX, you access and edit files directly. With ESXi, you need to copy those files to your management computer, edit the files locally, and then copy those files back to the host with vifs.

vifs can be used to access host files such as esx.conf, which is discussed further in Chapter 11, “Under the Hood with the ESXi Tech Support Mode.” When accessing files on a datastore, you should specify the path in either the datastore format of [datastore] path/file or with the full path, such as /vmfs/volumes/datastore/path/file. To avoid problems with special characters or spaces, ensure that you enclose the path in quotes.

To list the datastores for your ESXi host, issue the following command:

vifs --listds

To create a directory and then copy the file from your computer to your host, you would use the following commands:

vifs --mkdir '[datastore1] ISO_images'
vifs --put Linux.iso '[datastore1] ISO_images/Linux.iso'

Note that when you copy of a file to a datastore, you must specify the destination file name.

If you have an existing virtual machine and want to make a copy of it, you would follow this procedure:

  1. Copy the vmx file to your management computer to update any configuration settings:

    vifs --get '[Datastore1] LINUX01/LINUX01.vmx' LINUX02.vmx
    
  2. After you have edited the vmx file, you need to copy it back to the ESXi host. Execute the following commands to create a folder for the new virtual machine and to copy the vmx file to that folder:

    vifs --mkdir '[Datastore1] LINUX02'
    vifs --put LINUX02.vmx '[Datastore1] LINUX02/LINUX02.vmx'
    
  3. Next, copy the virtual disk file with the following command. If the source virtual machine is running, you should first create a snapshot with vmware-cmd:

    vmkfstools -i '[Datastore1] LINUX01/LINUX01.vmdk'
           '[Datastore1] LINUX02/LINUX02.vmdk'
    
  4. Once the virtual disk has been cloned, you can register the new virtual machine with the following command:

    vmware-cmd -s register '[datastore1] LINUX02/LINUX02.vmx'
    
  5. The last step is to start the virtual machine using the following commands. It is necessary to use the answer option with vmware-cmd because the host may recognize the new virtual machine as a copy of the source virtual machine:

    vmware-cmd '[datastore1] LINUX02/LINUX02.vmx' start
    vmware-cmd '[datastore1] LINUX02/LINUX02.vmx' answer
    

Monitoring Performance with resxtop

resxtop is included with the vCLI to provide detailed information on how ESXi is using resources in real time. You can use the utility in one of three modes: Interactive, Batch, and Replay. Replay Mode is covered further in Chapter 11. resxtop is included with the vCLI to replace esxtop, which you execute in the Service Console for ESX. With resxtop, you can quickly determine whether a certain resource is the cause of performance problems. resxtop is not available on the Windows version of the vCLI. For more information about interpreting the statistics that resxtop records, you can consult this VMware Communities document: http://communities.vmware.com/docs/DOC-11812. The Performance community on VMware’s forums contains a number of documents on troubleshooting specific performance issues.

With vSphere 4.1 resxtop has been enhanced and includes a number of improvements, such as the addition of NFS performance statistics. It is now possible to monitor NFS storage at the datastore level for a host, and at the datastore and virtual disk levels for a virtual machine.

When you start resxtop, it begins in Interactive Mode and displays CPU statics for the ESXi host. The data is refreshed every five seconds, but you can change that setting by pressing s and then entering the new interval in seconds. Be aware that excessive sampling, especially in Batch Mode, imposes a CPU load on the host.

To change views, you can use the following keys:

  • c: CPU

  • m: Memory

  • n: Network

  • i: Interrupts

  • d: Disk adapter

  • u: Disk device

  • v: Disk for virtual machines

  • p: Power management

  • V: Display only virtual machine worlds

You can press h to get a full list of command options. You may choose to re-sort the column order, sort the data in a specific order, or remove some columns. To save the customizations that you make, press W and you are prompted to save a configuration file, as follows:

Save config file to (Default to : /home/vi-admin/.esxtop41rc):

With Batch Mode, you can capture data for further performance analysis. The following command enables Batch Mode with the -b option. The -c option specifies the configuration file to use, -n instructs resxtop to collect 500 iterations of data, and -d sets the collection delay to five seconds. The command collects 2500 seconds of performance data and pipes the data to the file output.csv.

resxtop -b -c .esxtop41rc -n 500 -d 5 > output.csv

After you have collected the data, you can use tools such as Windows Performance Monitor, Microsoft Excel, and esxplot to analyze the data. esxplot is available at http://labs.vmware.com/flings/esxplot and runs on Linux, OSX, and Windows. Start the esxplot application, select File > Import > Dataset and select the data file generated by resxtop. Then double-click on the hostname and select a performance metric to display as shown in Figure 8.9.

Viewing performance data with esxplot.

Figure 8.9. Viewing performance data with esxplot.

Scripting with the vCLI and the vSphere SDK for Perl

Many of the commands provided in the vCLI are useful for step-by-step troubleshooting or setup, but you will likely want to create more complex scripts to automate post-installation configuration or to update multiple hosts with the same change. The mcli utility from the vSphere SDK for Perl is useful for executing single commands against many hosts. Likewise, it is fairly straightforward to string together the vCLI commands into a single script. However, to exploit the power of the vSphere SDK for Perl, which is utilized by the vCLI, it is necessary to delve into Perl scripting and the SDK documentation.

With a simple loop in a script, you can execute your commands against a number of hosts, as shown in the following example:

#!/usr/bin/perl -w
for $i in "esx01" "esx02" "esx03"
    do
    echo "Adding NAS datastore for $i..."
    vicfg-nas --server $i --add --nameserver 192.168.1.100 --share /NFS2 NFS2
    vicfg-nas --server $i -l
done

You can also use the programing depth of the SDK to create scripts for functionality not provided for in the vCLI. For example, with the vicfg-user command, you can assign permissions only at the host level. With the script found in the VMware Communities discussion at http://communities.vmware.com/message/1560327, you can grant a user a role on any virtual machine running on your ESXi host. The script takes the options --vmname, --rolename, and --setuser.

setRoleToVM.pl --vmname SQL01 --rolename LocalAdmin
      --setuser "Mishchenkodave.mishchenko"

Assign role LocalAdmin to user Mishchenkodave.mishchenko
Authorization Role LocalAdmin Added To Mishchenkodave.mishchenko Successfully.

In Chapter 3, “Management Tools,” the new vSphere feature Storage input/output (I/O) Control was discussed. This is configured at the datastore level with the vSphere client, which can be tedious if you have a large number of datastores to configure. With the script provided at http://www.virtuallyghetto.com/2010/07/script-automate-storage-io-control-in.html, the configuration of Storage I/O Control is accomplished with a vSphere SDK for Perl script. You can enable, configure, or disable the feature, and because the change is made in a script, it can be run repeatedly with little chance of error.

As you look to develop your own scripts, you should also review the utilities that are included with the SDK. These tend to be less host-centric than the vCLI commands and expose the richness of functionality that is available with the SDK. Documentation on the SDK utilities can be found at http://www.vmware.com/support/developer/viperltoolkit/viperl41/doc/vsperl_util_index.html.

For more reference material on the vSphere SDK for Perl, you can refer to this link: http://www.vmware.com/support/developer/viperltoolkit/.

Conclusion

Since the initial release of the RCLI for ESX and ESXi 3.5, VMware has made significant strides to provide feature parity in the vCLI when compared with the Service Console on ESX. With this release of the vCLI and vSphere 4.1, veteran users of the Service Console can find a suitable replacement.

With the vMA VMware provides an easy to deploy appliance that includes the vCLI and the vSphere SDK for Perl. The additional components of vi-fastpass and vi-logger, which are based on the SDK, provide convenient tools to handle authentication and logging.

To extend your scripting capabilities beyond the vCLI, VMware provides the vSphere SDK for Perl. With the SDK, you can automate many of the tasks you perform manually with the vSphere client.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.171.5