Last active
January 20, 2023 04:21
-
-
Save olomor/cc970f5fe7cfb9dce3e24aaa02658e78 to your computer and use it in GitHub Desktop.
Scripts to mantain a local host list (/etc/hosts) updated with all servers IPs at the same network, using a broadcast message containg "hostname and ip" over UDP:15000.
This file contains 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
# ========================= | |
# SUBSCRIBER | |
# ========================= | |
cat << 'EOF' >/usr/local/sbin/broadcastHostnameSubscriber.sh | |
#!/bin/bash | |
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin | |
sleep $((RANDOM%15)) | |
for IP_ADDRESS in $(ip address show up |grep -E 'inet [0-9]' |grep -v '127.0.0.1' |sed -r 's:(^.*inet )([0-9].*)(/.*):\2:g') | |
do | |
echo "${IP_ADDRESS} $(hostname -s)" |socat - udp-datagram:255.255.255.255:15000,broadcast,reuseaddr | |
done | |
EOF | |
chmod 700 /usr/local/sbin/broadcastHostnameSubscriber.sh | |
cat << 'EOF' >>/etc/cron.d/broadcastHostname | |
* * * * * root /usr/local/sbin/broadcastHostnameSubscriber.sh | |
EOF | |
# ========================= | |
# PUBLISHER | |
# ========================= | |
cat << 'EOF' >/usr/local/sbin/broadcastHostnamePublisher.sh | |
#!/bin/bash | |
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin | |
while true | |
do | |
while read -a M | |
do | |
eval "grep '${M[@]}' /etc/hosts" || { | |
sed -r "/${M[1]}/d" -i /etc/hosts | |
echo "${M[@]}" >>/etc/hosts | |
} | |
ps --format=pid,cmd |grep 'nc -l -u -p 15000 --recv-only' |grep -v grep |awk '{print $1}' |xargs kill | |
done< <(nc -l -u -p 15000 --recv-only) | |
[[ $SECONDS -gt 58 ]] && break | |
done | |
EOF | |
chmod 700 /usr/local/sbin/broadcastHostnamePublisher.sh | |
cat << 'EOF' >>/etc/cron.d/broadcastHostname | |
* * * * * root /usr/local/sbin/broadcastHostnamePublisher.sh | |
EOF |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment