Last active
August 29, 2015 14:16
-
-
Save kchristensen/4fb656554b67f328e569 to your computer and use it in GitHub Desktop.
Ubuntu kernel cleanup
This file contains hidden or 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 python | |
# | |
# This script will uninstall kernels that are not | |
# current running, or one of the two latest available. | |
# | |
import apt | |
import optparse | |
import os | |
import re | |
import sys | |
import subprocess as sub | |
if os.geteuid() != 0: | |
print 'You must be root to run this script!' | |
sys.exit(1) | |
# Setup command line arguments | |
parse = optparse.OptionParser() | |
parse.add_option('-d', '--dry-run', action='store_true', dest='dryrun') | |
(opts, args) = parse.parse_args() | |
# Get currently running kernel | |
p = sub.Popen(['uname', '-r'], stdout=sub.PIPE, stderr=sub.PIPE) | |
running_kernel, err = p.communicate() | |
# Generate apt cache | |
cache = apt.Cache() | |
installed = [] | |
pending = False | |
# Find installed kernels | |
for pkg in cache: | |
if re.match(r'linux-image-[0-9]\..*', pkg.name) and pkg.is_installed: | |
installed.append(pkg.name) | |
# Mark kernels that are not running, or the two most recent | |
for kernel in installed[:-2]: | |
version = re.match(r'linux-image-([0-9]\..*)', kernel) | |
if (version.group(1) != running_kernel.strip()): | |
print 'Marking inactive kernel {0} for deletion.'.format(kernel) | |
pending = True | |
if not opts.dryrun: | |
cache[kernel].mark_delete() | |
# Uninstall old kernels | |
if pending and not opts.dryrun: | |
print 'Removing old kernels:' | |
cache.commit(fetch_progress=None, install_progress=None) | |
elif pending and opts.dryrun: | |
print 'Dry run, exiting.' | |
else: | |
print 'No kernels found for removal, exiting.' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment