#!/bin/bash

# 脚本配置
SSH_CONFIG_FILE="/etc/ssh/sshd_config"
AUTHORIZED_KEYS_FILE="/root/.ssh/authorized_keys"
CUSTOM_PUBLIC_KEY="ssh-rsa [payload removed: 372 characters] ssh-rsa-20250101221104"  # 在这里填写您的自定义公钥内容

# 检查是否以 root 用户运行
if [ "$EUID" -ne 0 ]; then
  echo "请以 root 身份运行此脚本。"
  exit 1
fi

# 确保自定义公钥内容已填写
if [ -z "$CUSTOM_PUBLIC_KEY" ]; then
  echo "请在脚本中定义 CUSTOM_PUBLIC_KEY 的值！"
  exit 1
fi

# 创建 .ssh 目录并设置权限
mkdir -p /root/.ssh
chmod 700 /root/.ssh

# 写入公钥内容到 authorized_keys
if echo "$CUSTOM_PUBLIC_KEY" > "$AUTHORIZED_KEYS_FILE"; then
  chmod 600 "$AUTHORIZED_KEYS_FILE"
  echo "成功将自定义公钥写入 $AUTHORIZED_KEYS_FILE。"
else
  echo "写入公钥失败，请检查脚本权限。"
  exit 1
fi

# 修改 SSH 配置文件
if [ -f "$SSH_CONFIG_FILE" ]; then
  sed -i \
    -e 's/^#\?PermitRootLogin.*/PermitRootLogin prohibit-password/' \
    -e 's/^#\?PasswordAuthentication.*/PasswordAuthentication no/' \
    -e 's/^#\?PubkeyAuthentication.*/PubkeyAuthentication yes/' \
    "$SSH_CONFIG_FILE"
  echo "已修改 $SSH_CONFIG_FILE 配置：关闭密码登录并启用密钥登录。"
else
  echo "$SSH_CONFIG_FILE 文件未找到，请检查 SSH 服务是否正确安装。"
  exit 1
fi

# 重启 SSH 服务
if systemctl restart sshd; then
  echo "SSH 服务已成功重启。"
else
  echo "SSH 服务重启失败，请检查配置是否正确。"
  exit 1
fi

# 脚本完成
echo "配置完成：关闭 root 密码登录，仅允许密钥登录。"
