This Makefile automates the merging of the local /etc/hosts file with a remote /etc/hosts file obtained from a router at 192.168.15.1. The merged file ensures that duplicate entries are removed before updating the local /etc/hosts.
- Fetches the
/etc/hostsfile from a remote router. - Merges it with the local
/etc/hostsfile, removing duplicate entries. - Ensures the merged file is valid before updating
/etc/hosts. - Prevents updates if the merged file is unexpectedly empty or too small.
sshaccess to the router at192.168.15.1asroot.- GNU
makeinstalled. - The local user must have the necessary permissions to modify
/etc/hosts.
Place hosts.mk in /etc/hosts.mk:
sudo mv hosts.mk /etc/hosts.mkRun make to execute the default target, which merges and displays the merged hosts file:
make -f /etc/hosts.mkTo fetch and display the remote hosts file:
make -f /etc/hosts.mk cat-hostsTo view the merged hosts file:
make -f /etc/hosts.mk cat-merged-hostsTo apply the merged hosts file:
sudo make -f /etc/hosts.mk /etc/hosts.PHONY: cat-hosts cat-merged-hosts
cat-merged-hosts: /tmp/merged-hosts
cat $<
cat-hosts:
ssh [email protected] cat /etc/hosts
/tmp/remote-hosts:
ssh [email protected] cat /etc/hosts >$@
@test -s $@ || (echo "Error: $@ is empty. Aborting." && rm -f $@ && exit 1)
/tmp/merged-hosts: /tmp/remote-hosts
@test -s $< || (echo "Error: $< is empty. Aborting." && rm -f $< && exit 1)
cat /etc/hosts $^ | awk '!seen[$$0]++' > $@
@test -s $@ || (echo "Error: $@ is empty. Aborting." && rm -f $@ && exit 1)
/etc/hosts: /tmp/merged-hosts
@test -s $< || (echo "Error: $< is empty. Aborting." && rm -f $< && exit 1)
@filesize=$$(stat -c%s $<) && \
if [ $$filesize -ge 100 ]; then \
cp $< $@ && echo "Updated /etc/hosts"; \
else \
echo "Skipping update: $< is smaller than 100 bytes"; \
fiThis project is licensed under the MIT License.