centos设置指定网卡现在的动态ip为固定ip

环境:centos7
使用虚拟机时经常遇到虚拟机ip变化导致环境无法访问的问题,自己家用的服务器也会有这个问题。
下面这个脚本可以将系统自动获取的ip地址、网关等信息设置为固定ip,避免系统重启之后ip漂移导致无法访问。同时也避免网关信息设置错误导致网络无法访问。
将下面的代码保存为 setStaticIp.sh脚本,执行脚本setStaticIp.sh

echo 'please input the net device name';
read devName;
ipset=`ifconfig $devName|grep inet|awk 'BEGIN {FS=" "} {if($1=="inet") printf $2 "\n" $4 "\n" $6 "\n"}'`
ipset=($ipset)
gate=`route -n|grep $devName | awk 'BEGIN {FS=" "} {if($2 != "0.0.0.0") printf $2 "\n"}'`
echo IPADDR=${ipset[0]}
echo NETMASK=${ipset[1]}
echo GATEWAY=$gate
if test /etc/sysconfig/network-scripts/ifcfg-$devName; 
    then 
    cp /etc/sysconfig/network-scripts/ifcfg-$devName /etc/sysconfig/network-scripts/ifcfg-$devName-bk
    sed -i -e 's/^BOOTPROTO=\"dhcp\"/BOOTPROTO=\"static\"/' /etc/sysconfig/network-scripts/ifcfg-$devName
    sed -i '/IPADDR=/ d' /etc/sysconfig/network-scripts/ifcfg-$devName
    sed -i '/NETMASK=/ d' /etc/sysconfig/network-scripts/ifcfg-$devName
    sed -i '/GATEWAY=/ d' /etc/sysconfig/network-scripts/ifcfg-$devName
    echo IPADDR=${ipset[0]} >> /etc/sysconfig/network-scripts/ifcfg-$devName
    echo NETMASK=${ipset[1]} >> /etc/sysconfig/network-scripts/ifcfg-$devName
    echo GATEWAY=$gate >> /etc/sysconfig/network-scripts/ifcfg-$devName
fi

执行下面的命令重启网卡生效,不重启也没问题,下次系统重启的时候会自动执行固定ip的:

systemctl restart network

你可能感兴趣的:(centos,tcp/ip,linux,static,ip,固定ip设置,虚拟机)