The following script allows you to update your /etc/hosts file in a regular interval. By configuring a hostname and list of IPs, you can distribute requests to several hosts over time automatically. All you have to do is configure this script, add it to your crontab file, and point your application or script to the configured hostname.
In the example below, crontab is set to run the script every 3 hours (AIX style), but you can make it anything you would like. You could also do every few minutes instead of hours. Just be careful not to do it too frequently or update too many things at the same time, this is a sensitive system file after all (/etc/hosts). If you need anything beyond some basic spreading of connections, a more feature rich network load-balancer may be a better option.
Note: I added AIX to the title for a reason. Even though it is a bash shell script, it has a couple of AIX specific things. I only found the “hostent” tool to be available in AIX and the crontab format is also AIX (*/3 for Linux). Possibly in another post I can modify this script to just parse/replace the appropriate line in /etc/hosts instead of using the hostent command.
- New file: vi /home/scripts/next_host.sh
- Copy/Paste code below. Set DSTHOST and DSTARR. Save/Exit
- Executable: chmod 751 /home/scripts/next_host.sh
- Schedule to run: crontab -e (Copy/Paste “0 0,3,6…” in a new line)
- Have fun!
#!/bin/bash ################################################################### # Cron (every 3 hours): # 0 0,3,6,9,12,15,18,21 * * * /home/scripts/next_host.sh >/dev/null 2>&1 ################################################################### DSTHOST="DestinationHostName" declare -a DSTARR=("192.168.1.11" "192.168.1.12" "192.168.1.13") currentIP=$(hostent -s "$DSTHOST" | cut -f1) counter=0 for value in "${DSTARR[@]}" do if [ "$value" = "$currentIP" ] then nextIP="${DSTARR[$counter+1]}" fi ((counter++)) done if [ -z "$nextIP" ] then nextIP=${DSTARR[0]} fi hostent -a $nextIP -h "$DSTHOST" for value in "${DSTARR[@]}" do if [ "$value" != "$nextIP" ] then hostent -d $value fi done ping -q -c 1 $DSTHOST