1. 程式人生 > >Ubtunu 靜態IP設定 指令碼

Ubtunu 靜態IP設定 指令碼

參考連結https://www.jianshu.com/p/d69a95aa1ed7

 

#! /bin/bash

#開機自動配置ip
#address 192.168.176.123  
#netmask 255.255.255.0  
#broadcast 192.168.176.255
#gateway 192.168.176.2
#版本 1.0    作者 guocx 日期 2018-12-17

PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
export PATH


echo -e "自動配置IP中...";

address=192.168.176.126;
netmask=255.255.255.0;
broadcast=192.168.176.255;
gateway=192.168.176.2;


ens=$(cat /etc/network/interfaces | grep -v '#' | grep "ens..$" | cut -d ' ' -f2);		#獲取網絡卡名

if [ -z "$ens" ]; then		#如果ens資訊不存在的話 直接把預設資訊填入
	ens=ens32;
	echo "auto $ens" >> /etc/network/interfaces;
	echo "iface $ens inet static" >> /etc/network/interfaces;
	echo "address $address" >> /etc/network/interfaces;
	echo "netmask $netmask" >> /etc/network/interfaces;
	echo "broadcast $broadcast" >> /etc/network/interfaces;
	echo "gateway $gateway" >> /etc/network/interfaces;
	echo -e "ip預設資訊填入...";
else
	nowip=$(cat /etc/network/interfaces | grep -v '#' | grep 'address' | cut -d ' ' -f2);		#ip
	if [ -z $nowip ]; then
		sudo sed -i "$a address $address";
	elif [ "$nowip" != "$address" ]; then
		sudo sed -i "s/$nowip/$address/g" /etc/network/interfaces;
		echo -e "oldip: $nowip";
	fi
	echo -e "now ip: $address";

	nownetmask=$(cat /etc/network/interfaces | grep -v '#' | grep 'netmask'| cut -d ' ' -f2);	#netmask
	if [ -z $nownetmask ]; then
		sudo sed -i "$a netmask $netmask";
	elif [ "$nownetmask" != "$netmask" ]; then
		sudo sed -i "s/$nownetmask/$netmask/g" /etc/network/interfaces;
		echo -e "old netmsk: $nownetmask";
	fi
	echo -e "now netmask: $netmask";

	nowgateway=$(cat /etc/network/interfaces | grep -v '#' | grep 'gateway'| cut -d ' ' -f2);	#gateway
        if [ -z $nowgateway ]; then
                sudo sed -i "$a gateway $gateway";
        elif [ "$nowgateway" != "$gateway" ]; then
                sudo sed -i "s/$nowgateway/$gateway/g" /etc/network/interfaces;
                echo -e "old gateway: $nowgateway";
        fi
        echo -e "now gateway: $gateway";

        nowbroadcast=$(cat /etc/network/interfaces | grep -v '#' | grep 'broadcast'| cut -d ' ' -f2);	#broadcast
        if [ -z $nowbroadcast ]; then
                sudo sed -i "$a broadcast $broadcast";
        elif [ "$nowbroadcast" != "$broadcast" ]; then
                sudo sed -i "s/$nowbroadcast/$broadcast/g" /etc/network/interfaces;
                echo -e "old broadcast: $netmask";
        fi
        echo -e "now broadcast: $broadcast";
fi

echo -e "正在啟動網絡卡...";

sudo ip addr flush dev $ens		#重啟網路配置
sudo systemctl restart networking.service

exit 0;