Shell脚本自动修改Linux网卡地址、IP地址配置、主机名修改

时间:2022-09-12 16:56:40
#!/bin/bash
#Program:
# 修改网卡、修改IP地址
#History:
# ZhangXingbin First release 2015/07/14


#定义的一些常量
HOST_NAME='/etc/sysconfig/network'
HOSTNAME=`hostname`
ETH0='/etc/sysconfig/network-scripts/ifcfg-eth0'
RULES='/etc/udev/rules.d/70-persistent-net.rules'
#克隆虚拟机后,获取MAC地址
A_MAC_eth0=`cat /etc/udev/rules.d/70-persistent-net.rules | grep --color=auto 'eth0' | cut -d '"' -f 8`
A_MAC_Current=`ifconfig | grep --color=auto 'HWaddr' | cut -b 39-55`


#将MAC地址中的字母替换为小写
MAC_eth0=`tr '[A-Z]' '[a-z]' <<<"$A_MAC_eth0"`
MAC_Current=`tr '[A-Z]' '[a-z]' <<<"$A_MAC_Current"`


#打印获取到的MAC地址
echo "(1)对比MAC地址"
echo $MAC_eth0
echo $MAC_Current


#检查MAC地址是否需要修改
if [ $MAC_eth0 == $MAC_Current ]; then
echo "MAC地址不用修改!"
elif [ $MAC_eth0 != $MAC_Current ]; then
echo "请修改MAC地址为:${MAC_Current}!"      
        echo "需要修改的地方有${ETH0}以及${RULES}中eth0的MAC地址!"
        #修改ifcfg-eth0中的MAC地址
        echo "修改ifcfg-eth0中的MAC地址为${MAC_Current}..."
        sed -i "2c HWADDR=${MAC_Current}" ${ETH0}
        #修改后的ifcfg-eth0
        cat ${ETH0} | grep --color=auto "HWADDR"
        echo "ifcfg-eth0中的MAC地址修改完成!"
        #修改70-persistent-net.rules文件,将eth0的MAC地址改为eth1的
        #查看70-persistent-net.rules的信息
#cat ${RULES} | grep --color=auto "eth0"
        echo "修改70-persistent-net.rules文件"
        sed -i '8,$c SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR{address}=="'${MAC_Current}'", ATTR{type}=="1", KERNEL=="eth*", NAME="eth0"' ${RULES}
        #cat ${RULES} | grep --color=auto "eth0"
fi


#修改IP地址
#首先读取ifcfg-eth0文件
echo "${ETH0}的内容如下:"
cat ${ETH0}


#加入判断,先判断该文件中有没有IP地址
read -p "是否需要修改ifcfg-eth0文件(y/n):" yn
if [ "$yn" == "Y" ] || [ "$yn" == "y" ]; then
sed -i "5c ONBOOT=yes" ${ETH0}
sed -i "7c BOOTPROTO=static" ${ETH0}
#修改IP地址
read -p "输入IP地址:" IP
sed -i "7a IPADDR=${IP}" ${ETH0}
sed -i "8a NETMASK=255.255.255.0" ${ETH0}
read -p "输入GATEWAY地址:" GATE
sed -i "9a GATEWAY=${GATE}" ${ETH0}
#重启网卡
service network restart
#cat ${ETH0}
read -p "网络配置已完成,是否重启系统(y/n):" yn
if [ "$yn" == "Y" ] || [ "$yn" == "y" ]; then
        echo "将要重启系统..."
        reboot
elif [ "$yn" == "N" ] || [ "$yn" == "n"  ]; then
        echo "修改MAC地址后需要重启系统使之生效,请手动重启系统..."
fi


elif [ "$yn" == "N" ] || [ "$yn" == "n"  ]; then
echo "为了更好地使用网络还是修改一下吧!"
fi


#ping www.baidu.com


#修改主机名
read -p "当前主机名为${HOSTNAME},是否修改(y/n):" yn
if [ "$yn" == "Y" ] || [ "$yn" == "y" ]; then
        read -p "请输入主机名:" hdp
        sed -i "2c HOSTNAME=${hdp}" ${HOST_NAME}
read -p "主机名修改完成,重启系统使之生效,是否重启系统(y/n):" yn
if [ "$yn" == "Y" ] || [ "$yn" == "y" ]; then
        echo "将要重启系统..."
        reboot
elif [ "$yn" == "N" ] || [ "$yn" == "n"  ]; then
        echo "主机名修改后需要重启系统使之生效,请手动重启系统..."
fi
elif [ "$yn" == "N" ] || [ "$yn" == "n"  ]; then
        echo "主机名没有修改!"
fi