Sunday, 30 July 2017

Bash Script To Determine Retired Clients.

While in VDP you have a built in feature for unprotected VMs (That is VMs not added to VDP backup job) you might need a script to determine if VMs are missing from a backup job.

The script has a simple algorithm:
> The first time it runs it creates a file to gather all the protected client list
> The next time it runs it will check what is missing since the last protect client list.
> New added VMs will not be considered as Missing, however on Next iteration of script execution it will run a check to see if the new clients are missing.
> If you remove the first generated file for protected list post your second execution, then the third iteration will be void as it will generate a new protected client list.

The script has an email feature to send the output to a mailing address. If you want to exclude this, then discard line-21 to line-32. If you want to run the script as a cronjob, you can add it to crontab -e, but you cannot have manual email address input running in the script. You will have to create a constant for your email address and call it in the EOF.

The script can be accessed from my repository here:
https://github.com/happycow92/shellscripts/blob/master/missing-client.sh

The code {}

#!/bin/bash
IFS=$(echo -en "\n\b")
FILE=/tmp/protected_client.txt
if [ ! -f $FILE ]
then
client_list=$(mccli client show --recursive=true | grep -i /$(cat /usr/local/vdr/etc/vcenterinfo.cfg | grep vcenter-hostname | cut -d '=' -f 2)/VirtualMachines | awk -F/ '{print $(NF-2)}')
echo "$client_list" &> /tmp/protected_client.txt
sort /tmp/protected_client.txt -o /tmp/protected_client.txt
else
new_list=$(mccli client show --recursive=true | grep -i /$(cat /usr/local/vdr/etc/vcenterinfo.cfg | grep vcenter-hostname | cut -d '=' -f 2)/VirtualMachines | awk -F/ '{print $(NF-2)}')
echo "$new_list" &> /tmp/new_list.txt
sort /tmp/new_list.txt -o /tmp/new_list.txt
missing=$(comm -3 /tmp/protected_client.txt /tmp/new_list.txt | sed 's/^ *//g')
if [ -z "$missing" ]
then
printf "\nNo Client's missing\n"
else
printf "\nMissing Client is:\n" | tee -a /tmp/email_list.txt
printf "$missing\n\n" | tee -a /tmp/email_list.txt
printf "Emailing the list\n"
FILE=/tmp/email_list.txt
read -p "Enter Your Email: " TO
FROM=admin@$(hostname)
(cat - $FILE)<< EOF | /usr/sbin/sendmail -f $FROM -t $TO
Subject: Missing VMs from Jobs
To: $TO
EOF
sleep 2s
printf "\nEmail Sent. Exiting Script\n\n"
fi
rm /tmp/new_list.txt
rm -f /tmp/email_list.txt
fi

Feel free to reply for any issues. Hope this helps!