實驗環境:給本機IP設為192.168.100.100,腳本代碼如下:
可複制代碼如下:#!/bin/bash
yum install dhcp -y
network="/etc/sysconfig/network-scripts/ifcfg-ens33"
dhcp="/etc/dhcp/dhcpd.conf"
[ ! -e $network.bak ] && cp -p $network $network.bak
sed -i -e "4s/dhcp/static/" -e '$aIPADDR=192.168.100.100\nNETMASK=255.255.255.0\nGATEWAY=192.168.100.1' $network
systemctl restart network
cp -p /usr/share/doc/dhcp-4.2.5/dhcpd.conf.example $dhcp
[ ! -e $dhcp.bak ] && cp -p $dhcp $dhcp.bak
sed -i -e "29asubnet 192.168.100.0 netmask 255.255.255.0 {\n range 192.168.100.10 192.168.100.50;\n option routers 192.168.100.1;\n} " $dhcp
systemctl start dhcpd
詳解剖析
首先進行變量指派,指派給network和dhcp變量名
1、``[ ! -e $network.bak ] && cp -p $network $network.bak
判定是否已将network檔案備份,若無備份則執行備份操作
2、sed -i -e "4s/dhcp/static/" -e '$aIPADDR=192.168.100.100\nNETMASK=255.255.255.0\nGATEWAY=192.168.100.1' $network
systemctl restart network
将network檔案中的IP位址類型改為static,且在末行添加IPADDR=192.168.100.100,之後用“\n”另起一行;添加NETMASK=255.255.255.0,再用\n另起一行;添加GATEWAY=192.168.100.1
3、systemctl restart network
重新開機網絡服務
4、cp -p /usr/share/doc/dhcp-4.2.5/dhcpd.conf.example $dhcp