Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
cleaned up(?) script for rhel
#!/bin/bash
CONFIG_FILE="/etc/sysconfig/network"
function set_hostname() {
NAME=$1
[ -n "$NAME" ] || exit 0
sed -i '/^HOSTNAME=.*$/d' $CONFIG_FILE
echo "HOSTNAME=$NAME" >> $CONFIG_FILE
hostname $OS_HOST_NAME
}
function get_dns_name() {
first_ip=$(hostname -I | cut -d' ' -f1)
text=$(host $first_ip)
[ $? = 0 ] || exit 0
[[ $text == *"has no PTR record" ]] && exit 0
name=$(echo "$text" | awk '{print $(NF)}' | sed 's/\.$//')
echo $name
}
function split_name() {
OS_HOST_NAME=$( echo $FOUND_NAME | cut -f1 -d\. )
DOMAIN=$( echo $FOUND_NAME | cut -f2- -d\. )
export OS_HOST_NAME DOMAIN
}
function set_hosts_entry() {
# eth0 should always be assigned
# so we'll use it's IP for the main hosts entry
if [[ -z ${ETH0_IP} ]]; then
return 1
else
hosts_entry="${ETH0_IP} ${FOUND_NAME} ${OS_HOST_NAME}"
fi
# do nothing if entry is as expected
if grep -q "$hosts_entry" /etc/hosts ; then
return 0
fi
# modify the actual entry for this host, ensure ip and host are OK
if grep -v ^# /etc/hosts | grep -v 127.0 | grep -q ${OS_HOST_NAME} ; then
sed -i \
"s/.*${OS_HOST_NAME}.*/${hosts_entry}/" \
/etc/hosts
else
echo $hosts_entry >> /etc/hosts
fi
}
function set_resolv_entry() {
# add the domain to resolver's infos, this allows for proper resolution
if ! grep -q -E "^domain.*$DOMAIN" /etc/resolv.conf ; then
echo "domain $DOMAIN" >> /etc/resolv.conf
fi
}
#get_name() {
# hostname could've been passed in via variables
if [ -n "$SET_HOSTNAME" ]; then
FOUND_NAME=${SET_HOSTNAME}
# or be derived from DNS
elif [ -n "$DNS_HOSTNAME" ]; then
FOUND_NAME=$(get_dns_name)
else
# or missing
exit 1
fi
export FOUND_NAME
#}
# get_name &&
split_name $FOUND_NAME &&
set_hostname $FOUND_NAME &&
set_resolv_entry &&
set_hosts_entry
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment