#!/bin/bash
# CentOS 7 一键初始化脚本
# 功能:换源阿里云、安装基础工具、配置中文环境、安全加固、内核优化等
# 检查权限和网络
if [ "$(id -u)" != "0" ]; then
echo "必须使用root权限执行!" >&2
exit 1
fi
if ! ping -c 3 mirrors.aliyun.com &>/dev/null; then
echo "网络连接失败,请检查网络配置!" >&2
exit 1
fi
# 1. 更换阿里云YUM源
echo "正在配置阿里云YUM源..."
mkdir -p /etc/yum.repos.d/backup
mv /etc/yum.repos.d/*.repo /etc/yum.repos.d/backup/ &>/dev/null
curl -o /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo
curl -o /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo
sed -i 's/$releasever/7/g' /etc/yum.repos.d/CentOS-Base.repo
yum clean all && yum makecache
echo "YUM源已更新至阿里云源 "
# 2. 安装基础工具
echo "安装常用工具包..."
yum install -y vim wget curl lrzsz net-tools htop iftop sysstat tree git unzip &&
yum install dnf -y
dnf groupinstall "Development Tools"
echo "基础工具安装完成 "
# 3. 中文环境配置
echo "配置中文语言支持..."
yum install -y kde-l10n-Chinese glibc-common
localedef -c -f UTF-8 -i zh_CN zh_CN.utf8
echo 'LANG="zh_CN.UTF-8"' > /etc/locale.conf
source /etc/locale.conf
echo "中文环境已配置 "
# 4. 安全加固
echo "执行安全加固..."
# 关闭SELinux
sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config
setenforce 0
# 关闭防火墙
systemctl stop firewalld && systemctl disable firewalld
# 5. 内核优化
echo "优化系统内核参数..."
cat >> /etc/sysctl.conf <<EOF
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_max_tw_buckets = 5000
net.ipv4.tcp_syncookies = 1
vm.swappiness = 0
EOF
sysctl -p
echo "内核参数优化完成 "
# 6. 时间同步(改用chrony)
echo "配置时间同步..."
yum install -y chrony # 安装chrony替代ntpdate
# 配置chrony使用阿里云NTP服务器
sed -i 's/^server.*/server ntp.aliyun.com iburst/g' /etc/chrony.conf
# 启用并启动服务
systemctl enable chronyd && systemctl start chronyd
# 移除旧的cron任务(可选)
sed -i '/ntpdate/d' /etc/crontab
# 验证时间同步状态
echo "当前时间状态:"
chronyc tracking && echo "时间同步已配置 "
# 完成提示
echo "初始化完成!建议执行 reboot 重启系统使配置生效"
echo "验证命令:"
echo " - 源检查:yum repolist"
echo " - 语言验证:locale"
echo " - 时间验证:date"
适用于Linux开荒的脚本
于 2025-03-26 12:00:22 首次发布