LinuxInstallationDate

28th January 2016 at 11:57pm
Bash CodeSnippets

This script attempts to determine when a Linux host was installed. It does this by simply checking the root filesystem creation / format timestamp. It's a little clunky but it does the trick in most situations.

#!/bin/bash

PLATFORM="$(uname -s)"

case "${PLATFORM,,}" in
    linux)
        # http://free-electrons.com/blog/find-root-device/
        MAJOR_ROOTFS="$(mountpoint -d / | cut -f 1 -d ':')"
        MINOR_ROOTFS="$(mountpoint -d / | cut -f 2 -d ':')"
        DEV_ROOTFS="$(awk {'if ($1 == "'${MAJOR_ROOTFS}'" && $2 == "'${MINOR_ROOTFS}'") print $4 '} /proc/partitions)"
        if [ -r "/dev/$DEV_ROOTFS" ] ; then
            if [[ "$(dumpe2fs "/dev/$DEV_ROOTFS" 2>&1)" =~ [Ff]ilesystem\ [Cc]reated\ *:\ *([a-zA-Z0-9][a-zA-Z0-9:\ 0-]+) ]] ; then
                CREATED_ROOTFS="$(date -d "${BASH_REMATCH[1]}" +"%s")"
                if [[ "$CREATED_ROOTFS" =~ [0-9]+ ]] ; then
                    echo "$CREATED_ROOTFS"
                    exit 0
                fi
            fi
        fi

        # http://askubuntu.com/questions/1352/how-can-i-tell-what-date-ubuntu-was-installed
        if [ -r "/etc/lsb-release" ] ; then
            source "/etc/lsb-release"
            if [ "${DISTRIB_ID,,}" == "ubuntu" ] && \
                [[ "${DISTRIB_RELEASE%%.*}" -ge 12 ]] && \
                [ -d "/var/log/installer/" ] ; then
                for file in /var/log/installer/* ; do
                    MODIFIED_INSTALLER="$(stat -c "%Y" "$file")"
                    if [[ "$MODIFIED_INSTALLER" =~ [0-9]+ ]] ; then
                        echo "$MODIFIED_INSTALLER"
                        exit 0
                    fi
                done
            fi
        fi

        >&2 echo "Unknown installation date."
        exit 1
        ;;

    *)
        >&2 echo "Do not understand platform type $PLATFORM."
        exit 2
        ;;
esac