From 35e1272d3feeed97cafdc9e85a3a0768dc9dc335 Mon Sep 17 00:00:00 2001 From: ahdoawhfo Date: Sat, 21 Dec 2024 13:59:17 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=8C=E6=88=90=E4=BB=A3=E7=A0=81=E7=BC=96?= =?UTF-8?q?=E5=86=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- init.sh | 81 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 init.sh diff --git a/init.sh b/init.sh new file mode 100644 index 0000000..8278c40 --- /dev/null +++ b/init.sh @@ -0,0 +1,81 @@ +#!/bin/bash + +# 检查是否以 root 权限运行 +if [ "$EUID" -ne 0 ]; then + echo "[Init]请以 root 权限运行此脚本。" + exit 1 +fi + +# 随机生成SSH端口(20000到29999之间) +SSH_PORT=$((RANDOM % 10000 + 20000)) + +# APT更新 +echo "[Init]正在更新 APT..." +apt update && apt upgrade -y + +# Fail2ban 安装和配置 +echo "[Init]正在安装和配置 Fail2ban..." +apt install -y fail2ban rsyslog +systemctl enable fail2ban +systemctl start fail2ban + +# 创建一个简单的 Fail2ban 配置 +cat </etc/fail2ban/jail.local +#DEFAULT-START +[DEFAULT] +bantime = 600 +findtime = 300 +maxretry = 5 +banaction = iptables-allports +action = %(action_mwl)s +#DEFAULT-END + +[sshd] +ignoreip = 127.0.0.1/8 +enabled = true +filter = sshd +port = $SSH_PORT +maxretry = 5 +findtime = 300 +bantime = 600 +banaction = iptables-allports +action = %(action_mwl)s +logpath = /var/log/auth.log +EOF + +systemctl restart fail2ban +echo "[Init]Fail2ban 安装并配置完成!" + +# 配置 SSH 密钥登录和关闭密码登录 +echo "[Init]正在配置 SSH 密钥登录..." +SSH_DIR="/root/.ssh" +AUTHORIZED_KEYS="$SSH_DIR/authorized_keys" + +# 确保 .ssh 目录存在 +mkdir -p $SSH_DIR +chmod 700 $SSH_DIR + +# 导入公钥 +cat <$AUTHORIZED_KEYS +ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA4GtBuo9dezirPzwsmnyul3EwRWZFDweu1mCD7YCwt1QLFzjw3YYRpCTCDAoZOaKrV+G5W3awdidCCIWppi8QWjTG6SHvI0wo2Qszz6h5yr7znaRZlaBTKiCQsw7hhiFEVH69TclCFDNdkvbTn3cDAx8zBYYwiVnVBAqclnIlAWI9HQr8fCO5E2rJYQ4zaJZoiiJjNWk46bRtjvN1RyJ1Z1lX5zmYA6V5Wh9v54nSuI5zVlzzuox9sNJbyI3aLeBk37Z1Fc0GxkRwMlfuVHx6CZ/itHs8rVSv7oGVe+3yTu1SW2m+uVQtTXvh0+eFfajfVPpU69Jo0tOF2nlGlXkDBQ== +EOF +chmod 600 $AUTHORIZED_KEYS +echo "[Init]公钥已导入!" + +# 配置 SSHD +echo "[Init]正在配置 SSH 服务..." +sed -i.bak -e "s/^#*Port .*/Port $SSH_PORT/" \ + -e "s/^#*PasswordAuthentication .*/PasswordAuthentication no/" \ + -e "s/^#*PubkeyAuthentication .*/PubkeyAuthentication yes/" \ + -e "s/^#*PermitRootLogin .*/PermitRootLogin prohibit-password/" \ + /etc/ssh/sshd_config + +systemctl restart sshd +echo "[Init]SSH 配置完成!" + +# 显示新的 SSH 端口 +echo "[Init]所有步骤完成!请使用以下信息连接到您的服务器:" +echo "[Init]-----------------------------------------" +echo "[Init]SSH 端口:$SSH_PORT" +echo "[Init]密钥认证已启用,密码登录已禁用。" +echo "[Init]-----------------------------------------"