#!/bin/bash
echo "【1】修改命令提示符"
cat <<EOF >> /root/.bashrc

PS1='\[\e[35;40m\][\u@\h \W]#\[\e[0m\] '
EOF
[ "$?" -eq 0 ] && echo "    ----操作成功，执行source /root/.bashrc生效"

echo "【2】关闭防火墙"
systemctl stop firewalld &>/dev/null
systemctl disable firewalld &>/dev/null
[ "$?" -eq 0 ] && echo "    ----操作成功"

echo "【3】关闭selinux"
sed -i 's/enforcing/disabled/' /etc/selinux/config &>/dev/null
setenforce 0 &>/dev/null
echo "    ----操作成功"

echo "【4】关闭swap"
swapoff -a &>/dev/null
sed -ri 's/.*swap.*/#&/' /etc/fstab &>/dev/null
[ "$?" -eq 0 ] && echo "    ----操作成功"


echo "【5】优化SSH配置"
cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak
# 禁用DNS反向解析，加快SSH连接速度
sed -i 's/#UseDNS yes/UseDNS no/' /etc/ssh/sshd_config
sed -i 's/#GSSAPIAuthentication yes/GSSAPIAuthentication no/' /etc/ssh/sshd_config
# 修改会话超时时间
if ! grep -q "ClientAliveInterval" /etc/ssh/sshd_config; then
    echo "ClientAliveInterval 60" >> /etc/ssh/sshd_config
    echo "ClientAliveCountMax 3" >> /etc/ssh/sshd_config
fi
systemctl restart sshd &>/dev/null
[ "$?" -eq 0 ] && echo "    ----操作成功"

echo "【6】调整系统参数"
# 增大文件描述符限制
cat <<EOF >> /etc/security/limits.conf
* soft nofile 65535
* hard nofile 65535
* soft nproc 65535
* hard nproc 65535
EOF
# 调整内核参数
cat <<EOF >> /etc/sysctl.conf
# 避免放大攻击
net.ipv4.icmp_echo_ignore_broadcasts = 1
# 开启恶意icmp错误消息保护
net.ipv4.icmp_ignore_bogus_error_responses = 1
# 开启SYN洪水攻击保护
net.ipv4.tcp_syncookies = 1
# 允许TIME-WAIT状态sockets重用
net.ipv4.tcp_tw_reuse = 1
# 开启TCP连接快速回收
net.ipv4.tcp_tw_recycle = 1
# 减少FIN-WAIT-2状态的超时时间
net.ipv4.tcp_fin_timeout = 30
# 减少keepalive探测次数
net.ipv4.tcp_keepalive_probes = 3
# 缩短keepalive间隔
net.ipv4.tcp_keepalive_intvl = 15
# 缩短SYN连接超时时间
net.ipv4.tcp_syn_retries = 3
net.ipv4.tcp_synack_retries = 3
# 增大端口范围
net.ipv4.ip_local_port_range = 10000 65000
# 增大TCP缓冲区大小
net.ipv4.tcp_rmem = 4096 87380 6291456
net.ipv4.tcp_wmem = 4096 16384 4194304
net.core.rmem_max = 4194304
net.core.wmem_max = 4194304
net.core.rmem_default = 262144
net.core.wmem_default = 262144
net.core.optmem_max = 4194304
EOF
sysctl -p &>/dev/null
[ "$?" -eq 0 ] && echo "    ----操作成功"

echo "【7】清理不需要的服务"
for service in postfix avahi-daemon NetworkManager; do
    systemctl stop $service &>/dev/null
    systemctl disable $service &>/dev/null 2>&1
done
[ "$?" -eq 0 ] && echo "    ----操作成功"

echo "【8】做时间同步"
yum install ntpdate -y &>/dev/null
# 按顺序尝试，成功即停止
(ntpdate ntp.aliyun.com || \
 ntpdate ntp1.aliyun.com || \
 ntpdate ntp.tuna.tsinghua.edu.cn || \
 ntpdate ntp.ntsc.ac.cn || \
 ntpdate pool.ntp.org || \
 ntpdate time.windows.com || \
 ntpdate time.google.com) &>/dev/null
[ "$?" -eq 0 ] && echo "    ----操作成功" || echo "    ----所有时间服务器都同步失败"





echo "【其他】其他优化操作脚本"
echo "    ----frp客户端安装：curl -sSL https://www.klquan.com/scripts/tools/frpc.sh | bash"
echo "    ----yum设置阿里源：curl -sSL https://www.klquan.com/scripts/tools/set_yum.sh | bash"
