AWS启用root登录

#!/bin/bash
# AWS EC2 Root 密码登录一键脚本

set -e

echo "🔧 AWS EC2 一键启用 Root 密码登录"
echo "======================================"

# 输入密码
read -sp "请输入 root 密码: " ROOTPWD
echo
read -sp "再次确认密码: " ROOTPWD2
echo

if [ "$ROOTPWD" != "$ROOTPWD2" ]; then
    echo "❌ 两次密码不一致!"
    exit 1
fi

# 设置密码
echo "root:$ROOTPWD" | chpasswd
echo "✅ root 密码已设置"

# 修改配置
sed -i 's/^#*PasswordAuthentication.*/PasswordAuthentication yes/' /etc/ssh/sshd_config
sed -i 's/^#*PermitRootLogin.*/PermitRootLogin yes/' /etc/ssh/sshd_config

# 处理 cloud-init
mkdir -p /etc/ssh/sshd_config.d
cat > /etc/ssh/sshd_config.d/50-cloud-init.conf <<EOF
PasswordAuthentication yes
PermitRootLogin yes
EOF
echo "✅ SSH 配置已修改"

# 重启服务
systemctl restart ssh 2>/dev/null || systemctl restart sshd 2>/dev/null
echo "✅ SSH 服务已重启"

echo ""
echo "======================================"
echo "✅ 配置完成!可以使用密码登录了"

执行完后用这个命令检查:

sudo bash -c 'echo "=== SSH 配置检查 ==="; sshd -T | grep -E "passwordauthentication|permitrootlogin"; echo ""; echo "=== cloud-init 配置 ==="; cat /etc/ssh/sshd_config.d/50-cloud-init.conf 2>/dev/null || echo "无此文件"; echo ""; echo "=== SSH 服务状态 ==="; systemctl is-active ssh 2>/dev/null || systemctl is-active sshd'

正确输出应该包含:

passwordauthentication yes
permitrootlogin yes

安装 Fail2Ban(可选但推荐):

sudo apt update && sudo apt install fail2ban -y

 

滚动至顶部