Bash scripts with Expect scripts to control VMware ESXi using vim-cmd REMEMBER: the first ssh connection to a remote machine will ask a yes/no (to store the certificate)
!/bin/ash
if [ $# -ne 1 ]; then
echo "$# is the incorrect number of parameters for $0 , should be $0 vmname"
else
echo "searching for the VMID for $1"
VMID=vim-cmd vmsvc/getallvms | grep -i "$1" | cut -f 1 -d ' '
echo "$1 has a vmid of$VMID"
vim-cmd /vmsvc/snapshot.get $VMID
vim-cmd /vmsvc/snapshot.revert $VMID 0 0 0
vim-cmd /vmsvc/power.on $VMID
fi
!/bin/bash
if [ ! -f "/usr/bin/expect" ]; then echo "/usr/bin/expect is not found, please install with apt-get install expect" exit fi
USER="root" PASSWORD="password" REMOTEADDRESS=10.10.10.249 LOCATION="/home/ubuntu/ESXI" VMSCRIPTNAME="expect-get-vmid.sh" SNAPSHOTSCRIPTNAME="expect-display-vm-snapshots.sh" REVERTSCRIPT="expect-revert-to-snapshot-and-start-vm.sh"
RESULT=$($LOCATION/$VMSCRIPTNAME $USER $PASSWORD $REMOTEADDRESS) TRIMMEDRESULT=$(sed -e 's/^[[:space:]]*//' <<<"$RESULT") echo $TRIMMEDRESULT
$LOCATION/$SNAPSHOTSCRIPTNAME $USER $PASSWORD $REMOTEADDRESS $TRIMMEDRESULT > $LOCATION/vmid-snapshot-output.txt cat $LOCATION/vmid-snapshot-output.txt rm $LOCATION/vmid-snapshot-output.txt
$LOCATION/$REVERTSCRIPT $USER $PASSWORD $REMOTEADDRESS $TRIMMEDRESULT 0 0 0
!/usr/bin/expect
log_user 0 set timeout 1 set username [lindex $argv 0] set userpass [lindex $argv 1] set remoteaddress [lindex $argv 2] set command "vim-cmd vmsvc/getallvms | grep -i 'QA' | cut -f 1 -d ' '"
if { $argc < 3 } { puts "Wrong number of parameters, usage: script username password remoteaddress" exit }
spawn ssh $username@$remoteaddress $command expect "$username@$remoteaddress's password: " send "$userpass\n" interact
!/usr/bin/expect
log_user 0 set timeout 1 set username [lindex $argv 0] set userpass [lindex $argv 1] set remoteaddress [lindex $argv 2] set vmid [lindex $argv 3]
set command "vim-cmd /vmsvc/snapshot.get $vmid" if { $argc < 4 } { puts "Wrong number of parameters, usage: script username password remoteaddress vmid" exit }
spawn ssh $username@$remoteaddress $command expect "$username@$remoteaddress's password: " send "$userpass\n" interact
!/usr/bin/expect
log_user 0 set timeout 1 set username [lindex $argv 0] set userpass [lindex $argv 1] set remoteaddress [lindex $argv 2] set vmid [lindex $argv 3] set command "vim-cmd /vmsvc/snapshot.revert $vmid 0 0 0"
if { $argc < 4 } { puts "Wrong number of parameters, usage: script username password remoteaddress vmid" exit }
spawn ssh $username@$remoteaddress $command expect "$username@$remoteaddress's password: " send "$userpass\n" interact
set command "vim-cmd /vmsvc/power.on $vmid"
spawn ssh $username@$remoteaddress $command expect "$username@$remoteaddress's password: " send "$userpass\n" interact