CentOS7 更改网卡名称

系统安装完成后修改

本方法仅测试过单网卡,如果多网卡情况下更改网卡名需自己测试

替换网卡配置

# 修改配置文件中的硬件名称
sed -i "s/^NAME=.*/NAME=\"eth0\"/" /etc/sysconfig/network-scripts/ifcfg-ens33
sed -i "s/^DEVICE=.*/DEVICE=\"eth0\"/" /etc/sysconfig/network-scripts/ifcfg-ens33

# 更改硬件的配置文件名
mv /etc/sysconfig/network-scripts/ifcfg-ens33 /etc/sysconfig/network-scripts/ifcfg-eth0

更新Grub

如果是Grub2 方式启动 (判断是否存在 /etc/default/grub)

# 添加内核参数
kernel_options_post="net.ifnames=0 biosdevname=0"

# 更改Gurb 启动参数
TMP_GRUB=$(gawk 'match($0,/^GRUB_CMDLINE_LINUX="([^"]+)"/,a) {printf("%s\n",a[1])}' /etc/default/grub)
sed -i '/^GRUB_CMDLINE_LINUX=/d' /etc/default/grub
echo "GRUB_CMDLINE_LINUX=\"$TMP_GRUB $kernel_options_post\"" >> /etc/default/grub

# 更新参数到 Grub 配置文件
grub2-mkconfig -o /boot/grub2/grub.cfg

# 重启
reboot

如果是 Grub 方式启动

# 更新 Grub 启动参数
/sbin/grubby --update-kernel=$(/sbin/grubby --default-kernel) --args="$kernel_options_post"

# 重启
reboot

脚本判断执行

name=$(grep 'DEVICE' /etc/sysconfig/network-scripts/ifcfg-* | awk -F '"' '{print $2}'| head -1)
echo "需要修改的网卡名为:$name"
/bin/cp /etc/sysconfig/network-scripts/ifcfg-* /tmp
if [ -f "/etc/sysconfig/network-scripts/ifcfg-$name" ]; then
    sed -i "/^NAME=/d" /etc/sysconfig/network-scripts/ifcfg-$name
    sed -i "/^DEVICE=/d" /etc/sysconfig/network-scripts/ifcfg-$name
    sed -i '1i NAME="eth0"' /etc/sysconfig/network-scripts/ifcfg-$name
    sed -i '2i DEVICE="eth0"' /etc/sysconfig/network-scripts/ifcfg-$name
    /bin/cp /usr/lib/udev/rules.d/60-net.rules /etc/udev/rules.d/60-net.rules.bak
    /bin/mv /etc/sysconfig/network-scripts/ifcfg-$name /etc/sysconfig/network-scripts/ifcfg-eth0
    /bin/cp /etc/sysconfig/network-scripts/ifcfg-eth0  /tmp/ifcfg-eth0
fi

if [ -f /etc/default/grub ]; then
    kernel_options_post="net.ifnames=0 biosdevname=0"
    TMP_GRUB=$(gawk 'match($0,/^GRUB_CMDLINE_LINUX="([^"]+)"/,a) {printf("%s\n",a[1])}' /etc/default/grub)
    sed -i '/^GRUB_CMDLINE_LINUX=/d' /etc/default/grub
    echo "GRUB_CMDLINE_LINUX=\"$TMP_GRUB $kernel_options_post\"" >> /etc/default/grub
    grub2-mkconfig -o /boot/grub2/grub.cfg
else
    /sbin/grubby --update-kernel=$(/sbin/grubby --default-kernel) --args="$kernel_options_post"
fi
reboot

PEX 批量安装时更改

此方法在多网卡状态下也可正常使用

# PXE引导添加内核参数(net.ifnames=0 biosdevname=0)
KERNEL http://***/vmlinuz net.ifnames=0 biosdevname=0

# 无人值守自应答文件添加内核参数 (--append="net.ifnames=0 biosdevname=0")
bootloader --append=" crashkernel=auto" --location=mbr --boot-drive=sda --append="net.ifnames=0 biosdevname=0"