!/bin/bash
Author:小黑要上天
Date:2023/6
Description:系统初始化,包括:挂载镜像、搭建yum、设置主机名及IP地址和主机名映射、配置动态IP、关闭防火墙和selinux
Prerequisite:1.ISO镜像文件处于连接状态;2.网络为动态dhcp;3.适用于CentOS7
参数初始化
MOUNT_EXCEPTION=1
YUM_EXCEPTION=2
HOSTNAME_EXCEPTION=3
IP_EXCEPTION=4
FIREWALL_EXCEPTION=5
挂载镜像
function_mount()
{
umount /dev/cdrom &>/dev/null
mount /dev/cdrom /mnt &>/dev/null
if [ $? -eq 1 ];then
echo "镜像挂载失败,请人工干预"
exit $MOUNT_EXCEPTION
fi
echo "1.镜像成功挂载"
}
搭建yum
function_yum()
{
cd /etc/yum.repos.d
if [ ! -d bak/ ];then
mkdir bak
fi
mv -f *.repo bak/
cat >>CentOS7.repo </dev/null
yum clean all &>/dev/null
yum install -y finger-server initscripts net-tools &>/dev/null
echo "2.yum成功配置"
}
设置主机名
function_hostname()
{
read -p "请输入需要更改的主机名(E.g:centos79-3):" HN
if [ "$HN" == "" ];then
hostnamectl set-hostname "centos79-3" &>/dev/null
else
hostnamectl set-hostname $HN &>/dev/null
if [ $? -eq 1 ];then
echo "主机名设置失败,请人工干预"
exit $HOSTNAME_EXCEPTION
fi
fi
echo "3-1.主机名成功设置"
IP=$(ifconfig |grep inet | awk '{print $2}' | head -n 1)
host=$(hostname)
cat >>/etc/hosts <<EOF
$IP $host
EOF
echo "3-2.IP地址和主机名映射成功"
}
配置动态IP
function_ip()
{
read -p "请输入需要配置动态IP的网卡(E.g:ifcfg-ens32):" CARD
if [ "$CARD" == "" ];then
echo "网卡信息为空,请重新输入"
function_ip
else
cd /etc/sysconfig/network-scripts
count=$(find . -name "$CARD" -type f | wc -l)
if [[ $count -eq 1 ]] && [[ "$CARD" != "ifcfg-lo" ]] && [[ "$CARD" =~ ifcfg-.* ]];then
cp -f $CARD $CARD.bak.$(date +%Y%m%d%H%M%S)
sed -i '/IPADDR/d' $CARD && sed -i '/PREFIX/d' $CARD && sed -i '/GATEWAY/d' $CARD && sed -i '/DNS/d' $CARD && sed -i 's/BOOTPROTO="none"/BOOTPROTO="dhcp"/' $CARD && sed -i 's/BOOTPROTO="static"/BOOTPROTO="dhcp"/' $CARD
else
echo "网卡输入异常,请人工干预"
exit $IP_EXCEPTION
fi
fi
echo "4.网卡成功配置为dhcp"
}
关闭防火墙和selinux
function_firewall()
{
systemctl stop firewall &>/dev/null
systemctl disable firewalll &>/dev/null
cd /etc/selinux
sed -i 's/SELINUX=enforcing/SELINUX=disabled/' config
echo "5.防火墙和selinux成功关闭"
}
总结
function_summary()
{
echo
echo
echo "系统初始化已完成,请重启服务器(init 6 OR reboot)"
echo "检查:1.镜像挂载;2.yum搭建;3.主机名及IP地址和主机名映射设置;4.动态IP配置;5.防火墙和selinux关闭"
exit 0
}
main
function_mount
function_yum
function_hostname
function_ip
function_firewall
function_summary