VPS_Init/init.sh
2024-12-21 13:59:17 +08:00

82 lines
2.3 KiB
Bash
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/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 <<EOF >/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 <<EOF >$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]-----------------------------------------"