【玩转腾讯云】腾讯云CentOS 7.6升级内核到最新操作(附自动化Shell脚本)

2020-05-05 12:02:19 浏览数 (2)

最近腾讯云服务器即将到期,因为用了五年的服务器比较老了,而且云翼计划当年给的青岛配置相对续费便宜点,因此准备对其进行一下迁移。秉着自动化手段解决问题并且未来有更好的借鉴,对网上查找的升级内核操作进行了总结并脚本化处理。以供未来使用。

注意:本文首次撰写于2019-07-03,最近修改时间为2020-05-05,请注意相关程序的可用性与安全性。

简要说明脚本执行逻辑:

脚本一般需要执行三次,必须执行两次:

  1. 第一次执行进行yum update升级并重启。
  2. 第二次执行进行Kernel的正式升级与切换。
    • 这一步会进行两次的用户手工输入,第一次输入是选择最新内核所代表的最前面的数字,以便程序确认最新内核位置;
    • 第二步输入确认是否内核已经切换为第一步所输的数字,如果saved_entry=X中的X为第一步所输入的数字,即可输入y进行切换内核重启。
  3. 第三次(可选)执行进行旧内核的删除。当然也可以手工删除不执行此步骤。

代码如下:

代码语言:javascript复制
#!/bin/bash
#
# Title: CentOS7.6_x64_upgrade_kernel_script
# Author: ZNing
# Date: 2019-7-3 23:13:09
# Pass on the Tencent Cloud CentOS7.6 x64
# You should run this script three times. The first is yum update, the second is kernel upgrade to 5, the final one is optional when you decided to maunal which is deleting old kernel.
# Having fun to using it. (*^▽^*) Best wishes from Misaka Mikoto and Misaka 10086. 

clear;

function upgradeYum()
{
    yum clean all;
    yum update -y;
    reboot;
}

function upgradeKernel()
{
    rpm --import https://www.elrepo.org/RPM-GPG-KEY-elrepo.org;
    rpm -Uvh http://www.elrepo.org/elrepo-release-7.0-2.el7.elrepo.noarch.rpm;
    yum --disablerepo="*" --enablerepo="elrepo-kernel" list available;
    yum --enablerepo=elrepo-kernel install -y kernel-ml;
    grub2-mkconfig -o /boot/grub2/grub.cfg;
    grub2-editenv list;
    awk -F' '$1=="menuentry " {print i   " : " $2}' /etc/grub2.cfg;
    echo -n  "please enter the latest kernel number ->";
    read  num;
    grub2-set-default $num;
    grub2-editenv list;
}

function confirmKernel()
{
    echo -n  "are the kernel changed? If it is, plz input(y),else(n) ->";
    read confirmInput;
    if [ "$confirmInput" == 'y' ]; then
		reboot;
	elif [ "$selected" == 'n' ]; then
		exit;
	else
		confirmKernel;
		return;
	fi;
}

function removeOldKernel()
{
    IFS=$'n';
    for LINE in `rpm -qa | grep kernel- | grep 3.`; do
        #Do some works on "${LINE}"
        yum -y remove ${LINE};
    done;
    reboot;
}

function checkSystem()
{
    cat /etc/redhat-release;
    uname -sr;
    uname -a;
    echo "[Notice] Confirm Upgrade Kernel? please select: (1~4)"
    select selected in 'Upgrade Step 1' 'Upgrade Step 2' 'Delete Old Kernel' 'Exit'; do break; done;
	[ "$selected" == 'Exit' ] && echo 'Exit Upgrade.' && exit;
	if [ "$selected" == 'Upgrade Step 1' ]; then
		upgradeYum;
	elif [ "$selected" == 'Upgrade Step 2' ]; then
		upgradeKernel;
        confirmKernel;
	elif [ "$selected" == 'Delete Old Kernel' ]; then
		removeOldKernel;
	else
		ConfirmInstall;
		return;
	fi;
	echo "[OK] You Selected: ${selected}";
}

checkSystem;

0 人点赞