#!/bin/bash #dhcp install scripts ###判断dhcp是否安装、如已经安装就用原来的DHCP,如未安装帮其安装。 rpm -q dhcp &>/dev/null #判断是否安装了dhcp if [ $? -eq 0 ] ; then #判断rpm -q dhcp 的状态返回值是否等于0,如果等于0说明已经安装了 echo "DHCP have been installed " service dhcpd status &> /dev/null #检查dhcpd的运行状态,看是否运行 if [ $? -eq 0 ]; then #判断如果状态返回值等于0就停止dhcp服务,并拷贝参考配置文档到dhcpd.conf中。 echo "We are to topping the DHCP Svr" service dhcpd stop cat /usr/share/doc/dhcp-3.0.5/dhcp* > /etc/dhcpd.conf else #判断如果状态返回值不等于0,说明dhcp没有运行。那么同样将配置参考文档拷贝到dhcpd.conf中。 echo "DHCP svr is stopped" cat /usr/share/doc/dhcp-3.0.5/dhcp* > /etc/dhcpd.conf fi else #如果dhcp服务没有安装那么就安装 echo "DHCP havn't been installed, then we will install it" [ -d /media/Server ] || mount /dev/cdrom /media/ #判断如果有/media/Server目录,就不挂载/dev/cdrom,如果没有就挂载 [ -d /media/Server ] || echo "cdrom isn't mounted then exit" ; exit 11 #判断挂载是否成功,不成功就输出echo内容并退出,状态返回值设为11. rpm -ivh /media/Server/dhcp* --nodeps --force &> /dev/null #挂载成功则使用RPM方式安装dhcp服务 rpm -q dhcp &> /dev/null #检查dhcp是否安装 if [ $? -ne 0 ] ;then #判断状态返回值如果不等于0则输出下面echo内容并退出状态返回值设为12 echo "DHCP install is failly , then exit" exit 12 else #如果状态返回值等于0,则显示安装成功,并将配置参考文档拷贝到dhcpd.conf中。 echo "dhcp install was successfully." cat /usr/share/doc/dhcp-3.0.5/dhcp* > /etc/dhcpd.conf fi fi ####配置IP地址、子网掩码、网关 read -p "Pls put into the IP: " DIP #将输入的IP地址赋值给DIP read -p "Pls put into the NETMASK: " DMS #将输入的子网掩码赋值给DMS read -p "Pls put into the Gateway: " DGW #将输入的网关地址赋值给DGW DFILE="/etc/sysconfig/network-scripts/ifcfg-eth0" #将ech0网卡的配置文件赋值给DFILE grep -q "dhcp" $DFILE #使用grep查看网卡是否为dhcp自动获取IP if [ $? -eq 0 ]; then sed -i "s/BOOTPROTO=.*/BOOTPROTO=none/" #如果状态返回值等于0那么就将/BOOTPROTO=dhcp替换为BOOTPROTO=none cat <<! >>$DFILE #将cat值追加到变量DFILE中,也就是网卡配置文件。 NETMASK=$DMS IPADDR=$DIP GATEWAY=$DGW ! else #如果状态返回值不等于0,说明是静态配置IP的方式,那么将已有IP地址、子网掩码、网关替换为之前配置的 sed -i "s/NETMASK=.*/NETMASK=$DMS/" $DFILE sed -i "s/IPADDR=.*/IPADDR=$DIP/" $DFILE sed -i "s/GATEWAY=.*/GATEWAY=$DGW/" $DFILE fi service network restart &>/dev/null #重启网卡 ping -c 2 -i 0.1 -W 2 $DIP &> /dev/null #使用ping命令测试网卡是否重启成功,-c指定发两个包,-i指定发送间隔时间为1秒,-w指定不通等待2秒 if [ $? -eq 0 ]; then #如果状态返回值等于0,显示成功 echo "IP address have been set successfully." else #如果不等于0,显示失败并退出状态返回值设为13. echo "IP address have been set failly" exit 13 fi ####配置DHCP服务器 DNET=$(echo $DIP |awk -F. '{ print $1"."$2"."$3"."}') #使用awk过滤出服务器IP地址的前三段,-F. 以.为分隔符,将结果赋值给DNET sed -i "s/192.168.0./$DNET/g" /etc/dhcpd.conf #将dhcpd.conf中前三段为192.168.0 IP替换为变量DNET的值,也就是服务器IP地址的前三段 sed -i "s/192.168.1./$DNET/g" /etc/dhcpd.conf #需要替换那个就手动添加上即可 service dhcpd restart &>/dev/null #重启dhcpd if $(service dhcpd status &>/dev/null) ; then #使用if判断dhcpd的启动状态结果为0则为开启成功 echo "DHPC start OK!" #开启成功则显示start ok else #不为0说明启动失败,显示结果为start failly.退出状态返回值设为13 echo "DHCP start failly " exit 14 fi
转载于:https://blog.51cto.com/wangenzhi/1612724