Script to show if running kernel is outdated

Tux

I run Debian unstable on a few machines and wanted to know if I was always running the latest kernel. I've added the script below to my shell startup. And then I went on and added it to some servers as well, after a few hundred days of uptime there might have been an upgrade without reboot. Especially on machines that aren't redundant.

Raw
#!/usr/bin/env python3

"""
Print if the running kernel is the latest available. Should work on
Debian-based systems.

Needs the packaging package installed, pip install packaging
"""

import argparse
import glob
import os
import sys

try:
    from packaging.version import parse
except ImportError:
    sys.exit(12)


if sys.version_info.major == 3 and sys.version_info.minor <= 6:
    sys.exit(13)


LINUZ_PREFIX = "/boot/vmlinuz-"

parser = argparse.ArgumentParser(description="Show if running kernel is outdated")
parser.add_argument(
    "--minimal", "-m", action="store_true", help="Minimal output (for prompt)"
)
args = parser.parse_args()


def get_installed_versions():
    kernels = [
        linuz.replace(LINUZ_PREFIX, "") for linuz in glob.glob(f"{LINUZ_PREFIX}*")
    ]
    return [parse(kernel) for kernel in kernels]


def report(minimal=False):
    installed_versions = get_installed_versions()
    if not installed_versions:
        if minimal:
            sys.stdout.write("[🐧💥]")
        else:
            sys.stderr.write("PANIC. No kernels installed?\n")
        sys.exit(4)
    running_version = parse(os.uname().release)
    latest_version = max(installed_versions)
    is_latest = running_version == latest_version
    is_installed = running_version in installed_versions
    if is_latest and is_installed:
        if minimal is False:
            sys.stdout.write(f"{running_version} is the latest installed kernel\n")
        sys.exit(0)
    if not is_installed:
        if minimal:
            sys.stdout.write("[🐧😟]")
        else:
            sys.stderr.write(f"{running_version} is not installed\n")
        sys.exit(1)
    if not is_latest:
        if minimal:
            sys.stdout.write(f"[{latest_version}]")
        else:
            sys.stderr.write(
                f"{running_version} is not the latest kernel, {latest_version} is\n"
            )
        sys.exit(2)
    sys.exit(3)


if __name__ == "__main__":
    report(args.minimal)

0 comments

Start a new thread

Cancel reply
Markdown. Syntax highlighting with <code lang="php"><?php echo "Hello, world!"; ?></code> etc.
DjangoPythonBitcoinTuxDebianHTML5 badgeSaltStackUpset confused bugMoneyHackerUpset confused bugX.OrggitFirefoxWindowMakerBashIs it worth the time?i3 window managerWagtailContainerIrssiNginxSilenceTorWorldInternet securityFontGnuPGThunderbirdJenkins