June 30, 2009

Cut Your Exchange Backup Window in Half

Going all the way back to the Exchange 5.5 days, I've preferred doing disk-to-disk-to-tape Exchange backups. I'll use NTBackup for the disk-to-disk part, and the regular file backup agent that comes with whatever backup software we happen to be using for the to-tape part. This means eschewing the Exchange backup agents that most vendors provide, which in my mind is a big plus. Opinions will certainly vary, but using this method provides cost savings, fast restore times, extra protection and redundancy, and the reassurance that comes with using the native Exchange backup application. If you need more convincing, there are a few white papers from Microsoft describing this same setup as the Exchange backup method used by their in-house staff.

A client that is currently using this configuration has just surpassed the 200 GB mark for their combined mailbox store size, and the nightly full backups were taking a little longer than 6 hours to complete. This large backup window was preventing the nightly database maintenance tasks from completing, so a new strategy was in order. While thinking through some possibilities, I remembered reading about some registry tweaks that could improve the NTBackup performance when backing up to disk. After a little research, I made the changes, and the results were almost unbelievable: the Exchange backup job that had previously taken more than 6 hours to complete now finished in just under 2 1/2 hours!

While taking advantage of this dramatic speed boost only requires three registry changes and an additional command line parameter, there is a big bummer at first glance: the NTBackup registry keys that need to be changed reside in the HKEY_CURRENT_USER hive. This really cramps my style as I always configure the scheduled task that kicks off the NTBackup job as the NT AUTHORITY\SYSTEM account with a blank password. If you work in an environment with strict password change policies, even for system accounts, you know the pain of having to maintain passwords in scheduled tasks and scripts. Life is so much easier if it can just be avoided. But since the system account doesn't execute NTBackup interactively, the registry keys don't get created, and I assumed this meant there was no way to have the application check for the configuration tweaks.

But thankfully I was wrong, and it's a pretty simple process to manually create the necessary keys in the right spot:

  • First of all, you need to actually complete a backup job once to get the registry entries all set up, so as a regular administrator on the Exchange server, launch NTBackup, select a single temp file somewhere to backup, let the job run to completion, and then just delete the temporary backup set.

  • Launch regedit, and drill down to HKEY_CURRENT_USER\Software\Microsoft\Ntbackup\Backup Engine

  • You should already see the values we're about to change, if not, something didn't get created properly, so try a manual NTBackup job again. If the keys are present, make the following changes:

    • Change Logical Disk Buffer Size from 32 to 64

    • Change Max Buffer Size from 512 to 1024

    • Change Max Num Tape Buffers from 9 to 16

  • After making the changes, select the Backup Engine key from the left pane, and right click and select Export. Save it as a .reg file, and make sure Selected branch at the bottom of the Export window is set to HKEY_CURRENT_USER\Software\Microsoft\Ntbackup\Backup Engine

  • Now we'll locate the system account's registry settings, with regedit still open, browse to HKEY_USERS\S-1-5-18\Software\Microsoft\Ntbackup. The S-1-5-18 is the standard identifier for the system account, and unless you've scheduled NTBackup to run as NT AUTHORITY\SYSTEM before, the key will most likely be empty.

  • We need to schedule a job to run as NT AUTHORITY\SYSTEM to create the default keys, so launch NTBackup in advanced mode, select the Schedule Jobs tab, and set up a temp job to just back up any text file and schedule it to run in a couple of minutes from now. When prompted for the credentials that should be used for the job, you'll need to change the user account to NT AUTHORITY\SYSTEM with a blank password, several times. In fact, it still won't save it as the account to use, so after saving the scheduled job, open the task from the Scheduled Tasks panel and change the user account to NT AUTHORITY\SYSTEM with a blank password again.

  • After the job runs, you should see the following registry keys have been created under HKEY_USERS\S-1-5-18\Software\Microsoft\Ntbackup; Backup Engine, Backup Utility, Display, and Log Files. But if you drill into Backup Engine, you'll see it didn't create the keys we modified a few steps ago.

  • To easily create the keys, just edit the .reg file we exported earlier in Notepad. Change the line [HKEY_CURRENT_USER\Software\Microsoft\Ntbackup\Backup Engine] to [HKEY_USERS\S-1-5-18\Software\Microsoft\Ntbackup\Backup Engine], and save the file.

  • Now right click the .reg file, and select Merge. You should find the registry settings have been created for the system account, and NTBackup will now use the much speedier settings even when running as the system account.

There's another performance mod we need to make to give the backup even more boost. Since Windows Server 2003 Service Pack 1, NTBackup has been equipped with a secret and offensively named /fu switch, for 'file unbuffered' mode. To bolt this on, just edit the Scheduled Task for the NTBackup job, and add the /fu switch after the /hc:off parameter. When you're done, the Run: text box of the Scheduled Task will look something like this:


  C:\WINDOWS\system32\ntbackup.exe backup "@C:\Documents and Settings\
    Administrator\Local Settings\Application Data\Microsoft\Windows NT\
    NTBackup\data\Exchange_Daily.bks" /n "exchange_Backup.bkf created 
    6/30/2009 at 6:06 PM" /d "Set created 6/30/2009 at 6:06 PM" /v:no 
    /r:no /rs:no /hc:off /fu /m normal /j "Exchange_Daily" /l:s /f 
    "E:\exchange_ backups\exchange_Backup.bkf"


...read more

June 10, 2009

Configure a Vyatta Cluster for Redundant Virtual Firewalls

If you missed the Protect the Service Console Network With a Virtual Firewall project, we looked at how to use a Vyatta firewall to protect the ESX Service Console network and restrict SSH and VI or vSphere Client access to only a few specific workstations. Vyatta offers an impressive network operating system that can be run from a live CD, permanently installed on physical or virtual hardware, or downloaded as a virtual appliance. It comes with some high end features like stateful packet inspection, site-to-site VPN, OSPF, and BGP. There's a completely free edition with unrestricted access to all the features, but it can also be purchased with support offerings.

If you followed along with the original post, you may have noticed a potential pitfall: what if the ESX server hosting the Vyatta virtual machine goes down? You may have HA enabled, but what if it takes several minutes for the VM to boot all the way up on another host? Even a couple of minutes with no SSH or VM console access during a crisis would feel like an eternity.

Amazingly, the Vyatta operating system also includes clustering, and it's very simple to configure. To set up a cluster, we'll need the following:

  • Two Vyatta VC5 virtual machines, preferably with very similar configurations, see Protect the Service Console Network With a Virtual Firewall for a quick setup tutorial

  • Both Vyatta VMs will need two virtual NICs, each with its own real IP address: one in the Service Console network, and one in a LAN network

  • The clustered Vyatta VMs will host two virtual IPs: one will be the default gateway address configured on every ESX host (172.20.1.254 in our case), and the second will be a LAN address you specify as the route to the Service Console network on the Layer 3 device routing between your LAN subnets. In our case, we have a very simplified setup and the Vyatta's LAN facing interface is the default gateway for the LAN (10.1.1.254)

There's some good documentation on setting up a cluster in the High Availability Reference Guide for VC5 available for download at the Vyatta website.

Once you've got the two Vyatta VMs up and running on different ESX hosts, this is how the cluster configuration will look on the primary Vyatta firewall. We're using a conservative dead-interval of ten seconds, meaning a failover will only occur if keepalives are missed for that long, and keepalives are being sent out every two seconds over the eth0 (Console Network) interface.

The service commands define the virtual IPs the cluster will bring up on the secondary if the primary stops responding:

cluster {
    dead-interval 10000
    group sc-cluster {
        auto-failback true
        primary sc-firewall-pri
        secondary sc-firewall-sec
        service 10.1.1.254/24/eth1
        service 172.20.1.254/24/eth0
    }
    interface eth0
    keepalive-interval 2000
    pre-shared-secret ****************
}

interfaces {
    ethernet eth0 {
        address 172.20.1.252/24
        hw-id 00:50:56:9c:3b:0b
    }
    ethernet eth1 {
        address 10.1.1.252/24
        hw-id 00:50:56:9c:04:a5
    }
    loopback lo {
    }
}


And here's the cluster configuration on the secondary firewall. The actual cluster commands are identical, only the real IPs assigned to the interfaces are different:

cluster {
    dead-interval 10000
    group sc-cluster {
        auto-failback true
        primary sc-firewall-pri
        secondary sc-firewall-sec
        service 10.1.1.254/24/eth1
        service 172.20.1.254/24/eth0
    }
    interface eth0
    keepalive-interval 2000
    pre-shared-secret ****************
}

interfaces {
    ethernet eth0 {
        address 172.20.1.253/24
        hw-id 00:50:56:9c:3c:e0
    }
    ethernet eth1 {
        address 10.1.1.253/24
        hw-id 00:50:56:9c:38:04
    }
    loopback lo {
    }
}

As you can see, it's pretty simple to set up, but one annoyance with the cluster feature is that you have to create the same firewall rules on each device, there's no functionality for syncing up the configurations.

It wasn't too hard to write a quick and dirty little shell script to copy just the firewall configuration from the primary to the secondary, however, so you only need to maintain the rules on the primary, and then remember to run the script after saving the changes. If you like, you can set up public key authentication for SSH access from the primary to the secondary like we did in DIY ESX Server Health Monitoring - Part 2, but it's not necessary, the script will prompt you for the password during the SSH connection attempt.


#!/bin/bash

# Vyatta cluster firewall sync script
# by Robert Patton - 2009
#
# Copies firewall rules from primary to secondary
# and applies them to the appropriate interfaces.
#
# Deletes existing firewall rules on secondary and
# removes any firewall sets on interfaces, so make
# sure this is only run from the primary.
#
# Replace the SECONDARY value with the hostname or IP
# of the secondary device in the cluster.

SECONDARY="sc-firewall-sec"

TEMPFWRULES=$(mktemp TEMPFWRULES.XXXXXXXX)
TEMPINTCMDS=$(mktemp TEMPINTCMDS.XXXXXXXX)
TEMPSETCMDS=$(mktemp TEMPSETCMDS.XXXXXXXX)

# Match just the firewall section from the boot config file
awk '/^firewall {/, /^}/' /opt/vyatta/etc/config/config.boot > $TEMPFWRULES

# Match the interface section, we filter for firewall set statements later
awk '/^interfaces {/, /^}/' /opt/vyatta/etc/config/config.boot > $TEMPINTCMDS

# Create a script to run on the secondary with the firewall set commands
# The vyatta-config-gen-sets.pl script creates set commands from the config
cat > $TEMPSETCMDS <<'EOF1'
configure
# First remove any firewalls from interfaces
for int in $(show interfaces ethernet | \
awk '/eth[0-9]/ {print $1}'); \
do delete interfaces ethernet $int firewall; \
done
# Now delete all firewalls
for fwall in $(show firewall name | \
awk '/^ \w* {$/ {print $1}')
do delete firewall name $fwall; \
done
EOF1

cat >> $TEMPSETCMDS <<EOF2
# Create firewalls found on primary
$(/opt/vyatta/sbin/vyatta-config-gen-sets.pl $TEMPFWRULES)
# Apply firewalls to interfaces as defined on primary
$(/opt/vyatta/sbin/vyatta-config-gen-sets.pl $TEMPINTCMDS | grep firewall)
commit
save
exit
exit
EOF2

# Force a tty for the ssh connection - Vyatta environment variables
# and special shell are only set up during an interactive login
cat $TEMPSETCMDS | ssh -tt $SECONDARY

rm -f $TEMPFWRULES $TEMPSETCMDS $TEMPINTCMDS



...read more

June 5, 2009

Another ESX Server HTTP File Trick

While reading some docs on the vSphere CLI, I came across this note:

...you can browse datastore contents and host files using a Web browser. Connect to the following location:

http://ESX_host_IP_Address/host
http://ESX_host_IP_Address/folder

You can view datacenter and datastore directories from this root URL...


I knew you could browse the datastores this way as there is a link from the main welcome page, but the /host URL is news to me. Log in with the root account, and it brings up a page titled Configuration files with links to view a bunch of important - you guessed it - configuration files.

Not too terribly interesting, but I can already see myself hitting this URL just to get the vSphere license key or double check that the proper entries are in an ESX server's hosts file.

...read more

May 29, 2009

Instantly Serve an ESX Directory via HTTP


python -m SimpleHTTPServer 9090

Before you type that in, understand that it's not going to work unless you've made some ill-advised changes to the Service Console firewall. Also, make sure you fully grasp the security risk you're about to take. This command will start up a simple web server on TCP port 9090 in the current working directory, allowing anyone to browse the files and subdirectories from a web browser under the security context of the user that executed the command. In other words, if you execute this as the root user, in the root directory, any file in the Service Console can be downloaded from a web browser.

This one-liner is extremely dangerous, but it is also extremely handy, and if used correctly in a properly designed environment, the potential risks can be managed. I use this all the time in my test lab to get output files from scripts by simply cd'ing to the script directory, running the above command, and pointing a web browser to http://IP_OF_ESX:9090 from the vCenter server.

How to make it safer:
  • The ESX Service Console network should be completely isolated from the LAN, and only vCenter servers and specific administrative workstations are allowed access

  • The Python command should be executed while the working directory is a folder created just for this purpose, and only contains the specific files you want to share and no subdirectories

  • The command should only be executed by a non-root user and the web server torn down as soon as the files have been downloaded by issuing a Ctrl-C

  • The root user must open a specific port in the firewall prior to using the command; for example, to open TCP port 9090:

    esxcfg-firewall --openPort 9090,tcp,in,SimpleHTTP

  • The port should then be closed immediately after the needed files have been downloaded; for example, to close down the previous command:

    esxcfg-firewall --closePort 9090,tcp,in


This also works in ESX 3.5, but the version of Python in the Service Console lacks the -m option, so the path to SimpleHTTPServer.py must be specified:

# ESX 3.5
python /usr/lib/python2.2/SimpleHTTPServer.py 9090


Might be too dangerous for production, so consider the risks carefully. But for testing, it can be really handy.

...read more

May 26, 2009

VM Security in vSphere - Same Ol' Situation (S.O.S.)

Over the weekend, I had a chance to test out the directives for locking down the virtual machine security issues discussed in Hardening the VMX File with vSphere / ESX 4.0. Unfortunately, all of the security issues are still present in the GA release of vSphere, including non-privileged users having the ability to disconnect virtual NICs and change the time synchronization behavior.

I can't imagine why this situation still persists through version 4.0 of VMware's enterprise virtualization platform. Are there customers who prefer non-privileged user accounts retain this ability? And if so, couldn't we disable this functionality by default, and require .vmx directives to enable it?

Yes, it is easy to change the default settings, and any sysadmin worth his or her salary will make the changes and audit their environment for compliance. That's a tired argument, however, and better "out of the box" security should be a goal for any product. Anybody remember Windows 2000?

...read more

May 25, 2009

DIY ESX Server Health Monitoring - Part 4

If you're just catching this series on creating an ESX health report, in Part 1, Part 2, and Part 3 we set up everything we need to schedule the daily health check and send the results in a HTML formatted email. Running the health check once a day is probably not sufficient if you want to be on top of developing issues, however, and if you have a lot of ESX hosts, reading through a long list of performance statistics may be unreasonable. So to wrap this project up, we'll look at setting up a second cron job that will only send out an alert message when an ESX host exceeds a specified threshold.

Due to the simple design of the health report scripts, to set up this functionality we only need to modify a few lines from the run-esx-report.sh script:
  • The first change is in the loop where we SSH into each ESX host and run the esx-report.sh script. We'll simply change the append redirection symbols, >>, to the create or truncate symbol, >, this way we're creating a new report output file for each host, rather than a combined report. To be extra sure the temp file is truncated each time through the loop, we'll use the noclobber override option as well, so the >> symbols become >|

  • Next, we grep for the word WARNING in the output file, and wrap the rest of the script in an if statement so the email is only sent out if the grep command returns true

  • And finally, we'll just change the subject of the email message


###############################################################################
#
#  run-esx-threshold.sh
#
###############################################################################
#
#  To create the run-esx-threshold.sh script in the ~/esx-report directory,
#  copy this entire code segment into your shell.
#  If you'd rather copy just the script, select everything between the
#  SCRIPTCREATOR limit strings.
#
#  putty will ignore all the tabs, making the copied script quite ugly
#
###############################################################################

# If the ~/esx-report directory exists, cd to it so the script is created there
[ -d ~/esx-report ] && cd ~/esx-report

cat > ./run-esx-threshold.sh <<'SCRIPTCREATOR'
#! /bin/bash
  PATH="/bin:/usr/bin"

  if [ -z $1 ]; then
    echo "No ESX hosts specified, exiting"
    exit 1
  fi

  if ! pgrep ssh-agent >/dev/null; then
    echo "The ssh-agent process does not appear to be running, exiting"
    exit 1
  fi

  RUNDIR=$(dirname "$(which "$0")")

  source "${HOME}/.ssh-agent" >/dev/null || exit 1

  THISHOST=$(hostname | cut -d . -f 1)

  TEMPTEXT=$(mktemp "${RUNDIR}/temptext.XXXXXXXXXX")

  TEMPHTML=$(mktemp "${RUNDIR}/temphtml.XXXXXXXXXX")

  for host in $@; do
    if [ $(echo $host | cut -d . -f 1) = $THISHOST ]; then
      "${RUNDIR}/esx-report.sh" >| "$TEMPTEXT"
    else
      ssh -q $host "$(cat "${RUNDIR}/esx-report.sh")" >| "$TEMPTEXT" || \
        printf "WARNING: SSH connection to $host failed\n\n\n\n" >| "$TEMPTEXT"
    fi

    if grep WARNING "$TEMPTEXT" >/dev/null; then

      cat >| "$TEMPHTML" <<-'HEADEREOF'
	<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
	<html>
	<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<style type="text/css">
	body { font-family: monospace; font-size: 12px }
	pre { font-family: monospace; font-size: 12px }
	</style>
	</head>
	<body>
	<pre>
	HEADEREOF

      cat "$TEMPTEXT" | \
      sed -e 's/>/\&#62/g' \
          -e 's/WARNING:.*/<span style="color: red">&<\/span>/' >> "$TEMPHTML"

      cat >> "$TEMPHTML" <<-'FOOTEREOF'
	</pre>
	</body>
	</html>
	FOOTEREOF

      "${RUNDIR}/html-mailer.pl" -f esx-report@yourdomain.dom \
                                 -r administrator@yourdomain.dom \
                                 -s "Alert on $host" \
                                 -m exchange.yourdomain.com \
                                 -b "$TEMPHTML"
    fi
  done

  rm -f "$TEMPTEXT"; rm -f "$TEMPHTML"

SCRIPTCREATOR

chmod 0700 ./run-esx-threshold.sh

###############################################################################


Don't spam yourself
When considering how often you want to run the threshold check script, keep one shortcoming of this method in mind: if a parameter continues to exceed its threshold, the script will continue to email you every time it runs. If you set this up to run every five minutes, and head out into the woods over a holiday weekend, you're going to get a thousand alert messages before you get a chance to resolve the issue.

For our purposes, once every 30 minutes will suffice, and so we'll add another cron job by issuing a crontab -e command as the non-root user, press i to enter insert mode, and below the line containing the 7:10 AM ESX server health report job, we'll add:

0,30 * * * * ${HOME}/esx-report/run-esx-threshold.sh ESX LIST >/dev/null 2>&1

Press Esc, then :wq to write the crontab and exit vi, and we're done!

If you do want to run the threshold check every five minutes, instead of specifying a list like 0,5,10,15, etc., use the range of minutes followed by a forward slash and interval, like:

0-59/5 * * * * ${HOME}/esx-report/run-esx-threshold.sh ESX LIST >/dev/null 2>&1

Tweak the thresholds
You'll definitely want to play with the threshold settings from the esx-report.sh script in Part 1. The threshold is the third parameter supplied to the scale function, and I've highlighted it below for the memory usage check:

  printf "  Memory Usage:\n"
  (free | awk '/^Mem:/ {print $3, $2, "100", $1}
              /^Swap:/ {print $3, $2, "1", $1}') | \
    while read line; do scale $line; done

That does it for the DIY ESX Server Health Monitoring project, I hope you'll find this information easy to customize for your own environment. If you add new performance checks or enhancements, feel free to describe the changes in a comment.

Install it
If you'd like to set the whole thing up, just copy and paste each code segment with a light blue background into a putty session. To install:
  • Create the esx-report.sh script from Part 1 as the non-root user. Copying the entire code segment in the light blue box into a putty window will create the esx-report folder under the home folder of the user that executes it.

  • From Part 2, execute the ssh-keygen command as the non-root user. Then run the esxcfg-firewall command as root to open an outbound port for SSH. Create the two remaining scripts; copykey.sh, and start-ssh-agent.sh as the non-root user.
    Use copykey.sh to distribute the public key file, then launch ~/start-ssh-agent.sh to load the private key into memory, both as the non-root user. Make test ssh connections to each ESX host you need to run the report on, but make sure you source the .ssh-agent file first so the variables are exported to your shell, source ~/.ssh-agent

  • Now create the html-mailer.pl script from Part 3 as the non-root user. As root, run the esxcfg-firewall command to open outbound SMTP in the firewall. Change users back to the non-root user, and create the run-esx-report.sh script and change the email settings for your environment.

  • Create the run-esx-threshold.sh script from this post as the non-root user and change the email settings.

  • Set up the cron jobs for the daily health report and the threshold check. Customize the whole thing any way you see fit.

* A couple of tips:
  • Try to schedule the daily health check and threshold checks so they don't run at the same time. The jobs will run fine simultaneously, but the usage numbers could be inflated.

  • Configure reverse DNS records for your ESX hosts on the DNS servers they point to or you'll see long pauses during SSH connection attempts as the server times out attempting to resolve the connecting client's hostname from its IP.


...read more

May 19, 2009

DIY ESX Server Health Monitoring - Part 3

Updated: June 18, 2009
Added a semicolon to run-esx-report.sh that was left out and responsible for some ugly HTML formatting.

With the secure SSH access problem solved in Part 2, we'll move on to getting the data in the proper format and emailing it from the ESX Service Console. As you probably know, the Linux distribution installed with ESX 3.5 lacks sendmail or an equivalent command, but we can roll our own from a perl script.

The perl mailer script
We need to import two perl modules for the script, and both are included by default in the Service Console. Getopt::Std provides a simple way to get command line options, and Net::SMTP will interface with an Exchange or SMTP server accessible from the console network:

  use Getopt::Std;
  use Net::SMTP;

This getopt call is all that's necessary to declare the command line options (-f, -r, -s, etc.), and it will automatically populate a set of corresponding variables named opt_*. We'll do a quick check to make sure all the command line options were specified, and if not display the usage message:

  getopt ('frsmb');

  unless ($opt_f && $opt_r && $opt_s && $opt_m && $opt_b) {
    print_usage();
    exit 1;
  }

Next we'll create a filehandle named BODY, opening the file specified on the command line. After reading in each line to the variable body_data, we'll close the handle:

  open(BODY, $opt_b) || error("Could not open file $opt_b.");

  my @body_data=<BODY>;
  close(BODY);

The Net::SMTP module is pretty straightforward. To generate a HTML formatted email, we just need to specify the MIME version, the content type as HTML, and the character encoding as ISO 8859-1. If you would rather send the message as plain text, just remove those two lines:

  my $smtp = Net::SMTP->new($opt_m) ||
    error("SMTP connection to $opt_m failed.");
  $smtp->mail($opt_f);
  $smtp->to($opt_r);
  $smtp->data();
  $smtp->datasend("MIME-Version: 1.0\n");
  $smtp->datasend("Content-Type: text/html; charset=iso-8859-1\n");
  $smtp->datasend("To: $opt_r\n");
  $smtp->datasend("From: $opt_f\n");
  $smtp->datasend("Subject: $opt_s\n");
  foreach $line (@body_data)
    {
      $smtp->datasend("$line");
    }
  $smtp->dataend();
  $smtp->quit;

Here's the complete html-mailer.pl script:


###############################################################################
#
#  html-mailer.pl
#
###############################################################################
#
#  To create the html-mailer.pl script in the ~/esx-report directory, copy
#  this entire code segment into your shell.
#  If you'd rather copy just the script, select everything between the
#  SCRIPTCREATOR limit strings.
#
###############################################################################

# If the ~/esx-report directory exists, cd to it so the script is created there
[ -d ~/esx-report ] && cd ~/esx-report

cat > ./html-mailer.pl <<'SCRIPTCREATOR'
#! /usr/bin/perl -w

 use strict;
 use Getopt::Std;
 use Net::SMTP;

 # Options:
 # $opt_f  email address of the sender
 # $opt_r  recipient email address
 # $opt_s  message subject, enclose in quotes if spaces
 # $opt_m  SMTP server FQDN or IP address
 # $opt_b  HTML formatted file for the message body

  our ($opt_f, $opt_r, $opt_s, $opt_m, $opt_b);

  getopt ('frsmb');

  unless ($opt_f && $opt_r && $opt_s && $opt_m && $opt_b) {
    print_usage();
    exit 1;
  }

  open(BODY, $opt_b) || error("Unable to open file $opt_b");

  my @body_data=<BODY>;
  close(BODY);
  my $line;

  my $smtp = Net::SMTP->new($opt_m) ||
    error("SMTP connection to $opt_m failed");
  $smtp->mail($opt_f);
  $smtp->to($opt_r);
  $smtp->data();
  $smtp->datasend("MIME-Version: 1.0\n");
  $smtp->datasend("Content-Type: text/html; charset=iso-8859-1\n");
  $smtp->datasend("To: $opt_r\n");
  $smtp->datasend("From: $opt_f\n");
  $smtp->datasend("Subject: $opt_s\n");
  foreach $line (@body_data)
    {
      $smtp->datasend("$line");
    }
  $smtp->dataend();
  $smtp->quit;

sub error {
  my $msg = shift;
  print STDERR "html-mailer.pl: $msg\n";
  exit 1;
}

sub print_usage {
  print STDERR <<EOF

  html-mailer.pl - HTML Formatted Message Mailer

  Usage: html-mailer.pl -f FROM -r RECIP -s SUBJ -m SMTP_HOST -b HTML_FILE

  Sends an email to the specified address, filling the message body with the
  HTML formatted file specified.

EOF
}

SCRIPTCREATOR

chmod 0700 ./html-mailer.pl

###############################################################################


Enable outbound SMTP
Now that we've got a script that we can send test messages with, we need to enable outbound SMTP through the ESX firewall on the ESX server that will have the script scheduled from a cron job. Just type this command as root to open the port:

  # Execute as root
  esxcfg-firewall --openPort 25,tcp,out,SMTP


If your Exchange or SMTP server is reachable from the Service Console network, execute html-mailer.pl with the appropriate parameters, and specify any old text file:

  ./html-mailer.pl -f me@mydomain.dom \
                   -r me@mydomain.dom \
                   -s "Test message" \
                   -m exchange.mydomain.dom \
                   -b ./testfile.txt


The Service Console can't reach the Exchange server...
No worries, as long as you're able to reach the VirtualCenter server, we can install the SMTP service and set it up to forward to the Exchange server. To install SMTP on a Windows 2003 server, do the following:

  • Open the Control Panel > Add or Remove Programs > Add/Remove Windows Components > double click Application Server > and then double click Internet Information Server (IIS). Put a check next to SMTP Service and click OK, OK, and Next

  • After the SMTP install is complete, open the Start Menu > Programs > Administrative Tools > Internet Information Services (IIS) Manager, then right click Default SMTP Virtual Server and select Properties

  • In the General tab, drop down the IP address: to the IP address in the Service Console network, if different from the LAN. This will prevent the SMTP service from popping up on your network security guy's port scans :)

  • In the Access tab, click the Connection button, choose the Only the list below radio button, then click Add to add the appropriate subnet address and mask to the Group of computers option, or add each ESX server one at a time

  • In the Access tab again, click the Relay button, choose the Only the list below radio button, then click Add to add the appropriate subnet address and mask to the Group of computers option, or add each ESX server one at a time. Uncheck the option Allow all computers which successfully authenticate to relay

  • On the Delivery tab, click the Advanced button and add your Exchange server information in the Smart host: box. By specifying a smart host, the SMTP server will simply forward everything to the Exchange server, letting it make all the decisions about which domains to accept mail for, etc.

  • Now test out the SMTP forwarder by using telnet to initiate a SMTP session from the ESX server that will be sending the messages:
    
     telnet virtualcenter.lab.local 25
     ehlo
     mail from:spongebob@lab.local
     rcpt to:administrator@lab.local
     data
     Subject:test
     .
     quit
    

One script to rule them all
Almost there, so let's recap what we've done so far. In Part 1, we created the health check script that will run on each ESX server and send key performance stats and scaled histograms to the terminal. Then in Part 2, we covered how to distribute public keys so the script can be executed on several ESX servers via SSH. So far in Part 3, we've looked at a perl script that will email the combined script output, and now we need to create a script to tie it all together, and then schedule the script from a cron job.

Let's break down the main components of the script. First of all, if ssh-agent isn't running, the script isn't going to get very far, so we'll use pgrep to check for the process and exit if it's not found:

  if ! pgrep ssh-agent >/dev/null; then
    echo "The ssh-agent process does not appear to be running, exiting"
    exit 1
  fi

We need to source .ssh-agent, the file with the ssh-agent PID and socket info set up by the start-ssh-agent.sh script, or exit if it doesn't exist:

  source "${HOME}/.ssh-agent" >/dev/null || exit 1

Since we'll be running everything from an ESX Service Console, and that server is likely to be part of the health check, we should compare the list of ESX hosts to the local hostname so we don't open a SSH connection to the local machine. We use cut here to strip off the domain name so we'll match whether the FQDN or just the bare hostname is specified:

  THISHOST=$(hostname | cut -d . -f 1)

  for host in $@; do
    if [ $(echo $host | cut -d . -f 1) = $THISHOST ]; then
      "${RUNDIR}/esx-report.sh" >> "$TEMPTEXT"
    else
      ssh -q $host "$(cat "${RUNDIR}/esx-report.sh")" >> "$TEMPTEXT" || \
        printf "WARNING: SSH connection to $host failed\n\n\n\n" >> "$TEMPTEXT"
    fi
  done

After the health check script has looped through the list of ESX hosts, we'll start building the HTML file with the necessary tags. Setting the font size for the pre tag is the secret sauce for getting the email to display perfectly on a BlackBerry:

  cat > "$TEMPHTML" <<-'HEADEREOF'
	<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
	<html>
	<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<style type="text/css">
	body { font-family: monospace; font-size: 12px }
	pre { font-family: monospace; font-size: 12px }
	</style>
	</head>
	<body>
	<pre>
	HEADEREOF

If you need to use < or > symbols in a HTML document, you have to specify the actual ASCII code of the character, as HTML considers words wrapped in those symbols to be tags. We'll use a sed filter to replace all the >'s with the ASCII equivalent, and add a color tag to any lines with the word WARNING to make it stand out:

  cat "$TEMPTEXT" | \
  sed -e 's/>/\&#62/g' \
      -e 's/WARNING:.*/<span style="color: red">&<\/span>/' >> "$TEMPHTML"
Then we'll add the closing tags for everything to the end of the HTML file:

  cat >> "$TEMPHTML" <<-'FOOTEREOF'
	</pre>
	</body>
	</html>
	FOOTEREOF

And finally, we'll execute html-mailer.pl with the appropriate parameters. You'll need to change this section of the script for your environment:

  "${RUNDIR}/html-mailer.pl" -f esx-report@lab.local \
                             -r administrator@lab.local \
                             -s "ESX Health Report" \
                             -m lab-vc \
                             -b "$TEMPHTML"

Here's the run-esx-report.sh script. Remember to change the email address and mail server parameters for your environment:

###############################################################################
#
#  run-esx-report.sh
#
###############################################################################
#
#  To create the run-esx-report.sh script in the ~/esx-report directory, copy
#  this entire code segment into your shell.
#  If you'd rather copy just the script, select everything between the
#  SCRIPTCREATOR limit strings.
#
#  putty will ignore all the tabs, making the copied script quite ugly
#
###############################################################################

# If the ~/esx-report directory exists, cd to it so the script is created there
[ -d ~/esx-report ] && cd ~/esx-report

cat > ./run-esx-report.sh <<'SCRIPTCREATOR'
#! /bin/bash
  PATH="/bin:/usr/bin"

  if [ -z $1 ]; then
    echo "No ESX hosts specified, exiting"
    exit 1
  fi

  if ! pgrep ssh-agent >/dev/null; then
    echo "The ssh-agent process does not appear to be running, exiting"
    exit 1
  fi

  RUNDIR=$(dirname "$(which "$0")")

  source "${HOME}/.ssh-agent" >/dev/null || exit 1

  THISHOST=$(hostname | cut -d . -f 1)

  TEMPTEXT=$(mktemp "${RUNDIR}/temptext.XXXXXXXXXX")

  TEMPHTML=$(mktemp "${RUNDIR}/temphtml.XXXXXXXXXX")

  for host in $@; do
    if [ $(echo $host | cut -d . -f 1) = $THISHOST ]; then
      "${RUNDIR}/esx-report.sh" >> "$TEMPTEXT"
    else
      ssh -q $host "$(cat "${RUNDIR}/esx-report.sh")" >> "$TEMPTEXT" || \
        printf "WARNING: SSH connection to $host failed\n\n\n\n" >> "$TEMPTEXT"
    fi
  done

  cat > "$TEMPHTML" <<-'HEADEREOF'
	<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
	<html>
	<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<style type="text/css">
	body { font-family: monospace; font-size: 12px }
	pre { font-family: monospace; font-size: 12px }
	</style>
	</head>
	<body>
	<pre>
	HEADEREOF

  cat "$TEMPTEXT" | \
  sed -e 's/>/\&#62;/g' \
      -e 's/WARNING:.*/<span style="color: red">&<\/span>/' >> "$TEMPHTML"

  cat >> "$TEMPHTML" <<-'FOOTEREOF'
	</pre>
	</body>
	</html>
	FOOTEREOF

  "${RUNDIR}/html-mailer.pl" -f esx-report@yourdomain.dom \
                             -r administrator@yourdomain.dom \
                             -s "ESX Health Report" \
                             -m exchange.yourdomain.com \
                             -b "$TEMPHTML"

  rm -f "$TEMPTEXT"; rm -f "$TEMPHTML"

SCRIPTCREATOR

chmod 0700 ./run-esx-report.sh

###############################################################################


To cron foo, thanks for everything
Still with us? One more step, and it's an easy one. We'll add a cron job to run the script at 7:10 AM every morning. Remember to add the job for the user account you distributed SSH keys for.

To edit the cron entries for the user, type:

  crontab -e

This starts vi and opens up the user's crontab. To enter insert mode, type i

Assuming you've set everything up using the code segments used in this series, to add an entry for 7:10 AM, type this line, replacing ESX LIST with a space separated list of ESX hosts:

  10 7 * * * ${HOME}/esx-report/run-esx-report.sh ESX LIST >/dev/null 2>&1

After adding the entry, press the Esc key, and type :wq to write the crontab and quit.

If you have a long list of hosts, put them all in a text file, separated by spaces or each on its own line, and use command substitution to feed the list to run-esx-report.sh

  run-esx-report.sh $(cat ${HOME}/esx-report/hostlist.txt)

There's more?!
What if we wanted to trigger an email warning if an ESX host exceeds a threshold value? As we'll see in Part 4, we can do this easily with a quick modification to the run-esx-report.sh script.

...read more