实验环境:给本机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
将dhcp样本配置文件复制到dhcp配置文件中,实现全覆盖。
5、[ ! -e $dhcp.bak ] && cp -p $dhcp $dhcp.bak
判定是否已将dhcp配置文件备份,若无备份则执行备份操作
6、sed -i -e "29asubnet 192.168.100.0 netmask 255.255.255.0 {\n range 192.168.100.10 192.168.100.50;
在dhcp配置文件中添加网段、子网掩码、网关以及能给予的ip地址范围(可按需求自行更改)
7、ssystemctl start dhcpd
开启dhcpd服务
原文地址:https://blog.51cto.com/14475593/2441327
时间: 2024-10-08 01:49:22