Skip to content

Instantly share code, notes, and snippets.

@knappmk
Last active May 1, 2020 12:50
Show Gist options
  • Save knappmk/ad3041d4181e8ae60270016c249bfebc to your computer and use it in GitHub Desktop.
Save knappmk/ad3041d4181e8ae60270016c249bfebc to your computer and use it in GitHub Desktop.
Ubuntu allow hostnames - make sure that file owner and permissions are set correctly
5 * * * * bash -c "/etc/hostnames.sh"
# Used by script "hostnames.sh" which converts hosts.allow-styled entries with hostname to entries with equivalent ip-adresses
# Provide standard hosts.allow syntax with hostname
# Example: ALL:domain.org
ALL:sub.example.com # Person X
#!/bin/bash
cd /etc
SEPARATOR_START="### SECTION START - generated hostnames entries ###\n# This is a generated section. Do NOT edit (including comments)!"
SEPARATOR_END="### SECTION END ###"
hostip_config_string="${SEPARATOR_START}\n"
while IFS='' read -r line || [[ -n "$line" ]]; do
if [[ ! $line =~ ^\s*# && ! $line =~ ^\s*$ ]]; then
host_type=`echo $line | sed 's/^\([^:]*\):.*$/\1/g'`
hostname=`echo $line | sed 's/[^:]*:\([a-zA-Z_\.:~-]*\).*/\1/g'`
last_part=`echo $line | sed 's/[^:]*:[a-zA-Z_\.:~-]*\(.*\)/\1/g'`
hostname_ip=`getent hosts "$hostname" | awk '{ print $1 }'`
if [ -n "$hostname_ip" ]; then
hostip_config_string+="${host_type}:${hostname_ip}${last_part}\n"
fi
fi
done < "hostnames.allow"
hostip_config_string+=$SEPARATOR_END
FILE="hosts.allow"
sed -i ':a;N;$!ba;s/'"$SEPARATOR_START"'.*'"$SEPARATOR_END"'/'"$hostip_config_string"'/g' $FILE
if ! grep -zoq "${SEPARATOR_START/\\n/.}.*${SEPARATOR_END}" $FILE; then
printf "\n$hostip_config_string\n">>$FILE
fi
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment