Skip to content

Instantly share code, notes, and snippets.

@bgstack15
Created April 2, 2017 16:38
Show Gist options
  • Save bgstack15/846b7f36ca37b7dac971488377066bce to your computer and use it in GitHub Desktop.
Save bgstack15/846b7f36ca37b7dac971488377066bce to your computer and use it in GitHub Desktop.
list dhcp leases
#!/bin/sh
# 2017-04-02 12:30 quick and dirty ls-leases
# sed combine lines: http://stackoverflow.com/a/7853846/3569534
DEFAULT_LEASE_FILE=/var/lib/dhcpd/dhcpd.leases
leasefile="${DEFAULT_LEASE_FILE}"
#leasefile=/home/bgirton-local/foo
#sed -n '/^lease/,/^}/ { s/;' ${leasefile}
# the crazy sed removes leading and trailing whitespace, blank lines, and comments
declare -a leases
leases="$( sed -e 's/^\s*//;s/\s*$//;/^[#$]/d;s/\s*[^\]#.*$//;' "${leasefile}" | grep -viE "^$|^#" | sed -r -e '/server-duid/d;:a;/[;{]$/{N;s/\n//;ba}' )"
{ echo "${leases}"; echo "FINALLINE"; } | { \
printf "%-15s\t%-19s\t%-19s\t%s\n" "lease" "ends" "hw" "hostname"
while read line;
do
if ! test "${line}" = "FINALLINE";
then
lease="$( echo "${line}" | grep -oiE "lease.{10,30}\{" | cut -f2 -d' ' )"
ends="$( echo "${line}" | grep -oiE "ends.{10,30}\;" | tr -d ';' | cut -f3,4 -d' ' )"
hw="$( echo "${line}" | grep -oiE "hardware.{10,50}\;" | tr -d ';' | cut -f3 -d' ' )"
hostname="$( echo "${line}" | grep -oIE "client-hostname.{0,30}\;" | tr -d ';' | cut -f2 -d' ' )"
printf "%s\t%s\t%s\t%s\n" "${lease}" "${ends}" "${hw}" "${hostname}"
fi
done
} | column -t -s'\' | \
sort -k2,3 | tac | awk '!x[$4]++'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment