Last active
November 24, 2024 22:07
-
-
Save alexolinux/87df016bb554bfb3f2a59c855149f3b6 to your computer and use it in GitHub Desktop.
Shell script to look up DNS registers and catch up IPs being populated in /etc/hosts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/bin/bash | |
| labserver_list=( | |
| host1.mylabserver.com | |
| host2.mylabserver.com | |
| host3.mylabserver.com | |
| ) | |
| echo "Backing Up Hosts..." | |
| sudo cp -p /etc/hosts /etc/hosts.save | |
| temp_hosts=$(mktemp) | |
| count=1 | |
| for host in "${labserver_list[@]}"; do | |
| ip=$(dig @1.0.0.1 +short "$host" -4 -t A +time=5) | |
| # Check if dig returned a valid IP address | |
| if [[ -n "$ip" ]]; then | |
| echo -e "$ip \t acg-0$count \t k$count \t $host" >> "$temp_hosts" | |
| echo "Added $ip acg-0$count to temporary hosts file" | |
| else | |
| echo "Failed to resolve IP for $host (timeout or other error)" | |
| fi | |
| ((count++)) | |
| done | |
| if [ -s "$temp_hosts" ]; then | |
| # Remove existing entries and add new ones | |
| sudo awk ' | |
| NR==FNR { | |
| new_entries[$NF] = $0; | |
| next | |
| } | |
| $NF in new_entries { | |
| print new_entries[$NF]; | |
| delete new_entries[$NF]; | |
| next | |
| } | |
| {print} | |
| END { | |
| for (entry in new_entries) { | |
| print new_entries[entry] | |
| } | |
| } | |
| ' "$temp_hosts" /etc/hosts > /tmp/hosts.new | |
| sudo mv /tmp/hosts.new /etc/hosts | |
| fi | |
| rm -f "$temp_hosts" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment