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/hosts
file from a remote router. - Merges it with the local
/etc/hosts
file, 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.
ssh
access to the router at192.168.15.1
asroot
.- GNU
make
installed. - 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.mk
Run make
to execute the default target, which merges and displays the merged hosts file:
make -f /etc/hosts.mk
To fetch and display the remote hosts file:
make -f /etc/hosts.mk cat-hosts
To view the merged hosts file:
make -f /etc/hosts.mk cat-merged-hosts
To 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"; \
fi
This project is licensed under the MIT License.