Created
April 25, 2016 20:09
-
-
Save rajiteh/fb235a63e0e61ca223637964f9ba7da2 to your computer and use it in GitHub Desktop.
keep alive script to ensure dhclient is running all the time
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
#!/usr/bin/env bash | |
# This script should be run periodically to ensure that dhclient process is active. | |
pidfile_glob="/run/dhclient*" | |
regex="/run/dhclient\.([a-z]+[0-9]+)\.pid" | |
matched=0 | |
function _logger() { | |
logger "DHCLIENT KEEPALIVE: " $@ | |
echo "DHCLIENT KEEPALIVE: " $@ | |
} | |
for f in $pidfile_glob | |
do | |
if [[ $f =~ $regex ]] | |
then | |
matched=1 | |
interface="${BASH_REMATCH[1]}" | |
procs=$(ps -ef | grep dhclient | grep $interface | grep -v grep) | |
proc_count=$(echo "$procs" | wc -l) | |
if [[ "$proc_count" -gt "1" ]] | |
then | |
kill -9 $(echo "$procs" | awk '{print $2}') | |
procs="" | |
_logger "Multiple processes found and killed. ${interface}" | |
fi | |
proc=$(echo "$procs" | head -n 1) | |
pid="$(echo "$proc" | awk '{print $2}' )" | |
fpid="$(cat /var/run/dhclient.$interface.pid)" | |
if [[ "$pid" != "$fpid" ]] | |
then | |
_logger "PID mismatch: ${fpid}(${pid}) / ${interface}" | |
if [[ "$fpid" == "" && "$pid" != "" ]] | |
then | |
kill -9 $pid | |
_logger "PID Killed: ${pid} / ${interface}" | |
fi | |
if eval dhclient -1 -v -pf /run/dhclient.${interface}.pid -lf /var/lib/dhcp/dhclient.${interface}.leases ${interface}; then | |
_logger "Started: $(cat /run/dhclient.${interface}.pid) / ${interface}" | |
exit 0 | |
else | |
_logger "Error starting dhclient: ${interface}" | |
exit 1 | |
fi | |
else | |
echo "Process and pid match: ${proc}" | |
fi | |
fi | |
done | |
if [[ $matched == 0 ]] | |
then | |
interface=eth0 | |
_logger "No run files matched. Starting on ${interface}" | |
eval dhclient -1 -v -pf /run/dhclient.${interface}.pid -lf /var/lib/dhcp/dhclient.${interface}.leases ${interface} | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment