#!/usr/bin/perl
# Get list of ALL VM's
# (\d{1,2})\s+([\w\d\-]+).*\n
$cmdvmlist = "vim-cmd vmsvc/getallvms";
# RegEX for running VM's
# ([\d]+\-[\w\d\s\.]+)\n\s+World ID:\s(\d+)
$cmdvmrunning = "esxcli vm process list";
$esxhost = "root\@192.168.1.26";
$vmlist = `ssh $esxhost $cmdvmlist`;
#print $vmlist;
# ([\d]+\-[\w\d\s\.]+)\n\s+World ID:\s(\d+)
my @shutdownorder;
$count=0;
print "VM Inventory on $esxhost\n";
while ($vmlist =~ /(\d{1,2})\s+([\w\d\-]+).*\n/g)
{
# Don't shutdown the VM running this script until last as it also controls APCUPSD
if ($1 != 30)
{
$shutdownorder[$count] = $1;
$shutdownordername[$count] = $2;
$count++;
}
}
print "VMID\tName\n";
my $index;
for my $order (@shutdownorder) {
print "$order \t $shutdownordername[$index++]\n";
}
# If shutdown argument is present, shutdown VM's
if ($ARGV[0] eq "shutdown")
{
open (my $fh, '>', "/tmp/esxhostscript");
print "\nCreating Script for ESX Host\nUploading ";
while (@shutdownorder)
{
$vm = shift(@shutdownorder);
print $fh "vim-cmd vmsvc/power.shutdown $vm\n";
}
print $fh "shutdown +3\n";
close $fh;
# Copy script to ESX Host
system("scp","/tmp/esxhostscript","root\@192.168.1.26:/tmp/esxhostscript");
# Add Execute Permission
system("ssh","root\@192.168.1.26","chmod +x /tmp/esxhostscript");
# Execute Script
system("ssh","root\@192.168.1.26","/tmp/esxhostscript");
print "Waiting for VM's to shutdown\n";
while (CheckRunning())
{
print ".";
sleep 5;
}
print "\n\n";
# SHUTDOWN NAS
@nasshut1 = `ssh -p 9999 192.168.1.14 shutdown -h now`;
@nasshut2 = `ssh -p 9999 192.168.1.24 shutdown -h now`;
}
else
{
printf "shutdown argument not passed, no action taken\n"
}
sub CheckRunning
{
$vmrun = `ssh $esxhost $cmdvmrunning`;
while ($vmrun =~ /([\d]+\-[\w\d\s\.]+)\n\s+World ID:\s(\d+)/g)
{
if ($2 ne "91789")
{
return 1;
}
}
return 0;
}
No comments:
Post a Comment