Ubuntu 服务器清理多余内核

09/26/2017

Ubuntu Server 并无桌面环境,多次升级以后系统中会存在大量不同版本的内核,而每个内核占用非常多的硬盘空间(一般一个内核300mb左右占用),所以需要定期清理没用的内核。

1.查看当前使用的时哪个内核.

magth@cloud:~$ uname -a
Linux cloud 4.4.0-96-generic #119-Ubuntu SMP Tue Sep 12 14:59:54 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux

2.查看当前系统安装了多少内核

magth@magth:~$ dpkg --get-selections|grep linux
console-setup-linux				install
libselinux1:amd64				install
linux-base					install
linux-firmware					install
linux-generic					install
linux-headers-4.4.0-62				install
linux-headers-4.4.0-62-generic			install
linux-headers-4.4.0-92				install
linux-headers-4.4.0-92-generic			install
linux-headers-4.4.0-93				install
linux-headers-4.4.0-93-generic			install
linux-headers-4.4.0-96				install
linux-headers-4.4.0-96-generic			install
linux-headers-generic				install
linux-image-4.4.0-62-generic			install
linux-image-4.4.0-92-generic			install
linux-image-4.4.0-93-generic			install
linux-image-4.4.0-96-generic			install
linux-image-extra-4.4.0-62-generic		install
linux-image-extra-4.4.0-92-generic		install
linux-image-extra-4.4.0-93-generic		install
linux-image-extra-4.4.0-96-generic		install
linux-image-generic				install
linux-libc-dev:amd64				install
util-linux					install

3.一键清理多余内核命令

magth@magth:~$ dpkg -l 'linux-*' | sed '/^ii/!d;/'"$(uname -r | sed "s/\(.*\)-\([^0-9]\+\)/\1/")"'/d;s/^[^ ]* [^ ]* \([^ ]*\).*/\1/;/[0-9]/!d' | xargs sudo apt-get -y purge

4.内核清理完毕

magth@cloud:~$ dpkg --get-selections|grep linux
console-setup-linux				install
libselinux1:amd64				install
linux-base					install
linux-firmware					install
linux-generic					install
linux-headers-4.4.0-96				install
linux-headers-4.4.0-96-generic			install
linux-headers-generic				install
linux-image-4.4.0-96-generic			install
linux-image-extra-4.4.0-96-generic		install
linux-image-generic				install
linux-libc-dev:amd64				install
util-linux					install

4.还有一种情况,系统内核已经卸载了,但是并未实际删除显示状态为 deinstall ,清理命令为:

magth@cloud:~$ dpkg --get-selections | grep deinstall | sed 's/deinstall/\lpurge/' | sudo dpkg --set-selections; sudo dpkg -Pa