实验环境:给本机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