#!/bin/bash

# 简化版：检查并设置root登录限制
set_root_login_restrict() {
    local config_file="/etc/ssh/sshd_config"
    
    # 检查当前状态
    if grep -q "^PermitRootLogin no" "$config_file" 2>/dev/null; then
        echo "root远程登录已禁止"
        return 0
    fi
    
    # 备份配置
    sudo cp "$config_file" "${config_file}.backup.$(date +%s)"
    
    # 注释或替换现有的PermitRootLogin行
    sudo sed -i '/^PermitRootLogin/d' "$config_file"
    sudo sed -i '/^#PermitRootLogin/d' "$config_file"
    
    # 添加新的配置
    echo "# 禁止root远程登录 - 安全配置" | sudo tee -a "$config_file" > /dev/null
    echo "PermitRootLogin no" | sudo tee -a "$config_file" > /dev/null
    
    # 重启SSH服务
    if sudo systemctl restart sshd 2>/dev/null || sudo systemctl restart ssh 2>/dev/null; then
        echo "✓ 已禁止root远程登录"
        return 0
    else
        echo "✗ SSH服务重启失败"
        return 1
    fi
}

# 执行
set_root_login_restrict
