先使用almalinux用户,使用密钥登录。
执行sudo -i切换到root
然后上传以下脚本root.sh,执行bash root.sh就允许root用户登录了
bash
#!/bin/bash
# 最终修复脚本
echo "=== 开始最终修复 ==="
# 1. 清理配置片段
echo "清理配置片段..."
rm -f /etc/ssh/sshd_config.d/*-password*.conf 2>/dev/null
# 2. 备份并创建干净的配置
cp /etc/ssh/sshd_config /etc/ssh/sshd_config.before_final
cat > /etc/ssh/sshd_config << 'EOF'
Port 22
Protocol 2
HostKey /etc/ssh/ssh_host_rsa_key
HostKey /etc/ssh/ssh_host_ecdsa_key
HostKey /etc/ssh/ssh_host_ed25519_key
SyslogFacility AUTH
LogLevel INFO
LoginGraceTime 120
PermitRootLogin yes
StrictModes yes
PubkeyAuthentication yes
IgnoreRhosts yes
HostbasedAuthentication no
PermitEmptyPasswords no
ChallengeResponseAuthentication yes
PasswordAuthentication yes
X11Forwarding yes
X11DisplayOffset 10
PrintMotd no
PrintLastLog yes
TCPKeepAlive yes
AcceptEnv LANG LC_*
Subsystem sftp /usr/libexec/openssh/sftp-server
UsePAM yes
EOF
# 3. 修复PAM配置
cp /etc/pam.d/sshd /etc/pam.d/sshd.before_final
cat > /etc/pam.d/sshd << 'EOF'
#%PAM-1.0
auth required pam_sepermit.so
auth substack password-auth
auth include postlogin
account required pam_nologin.so
account include password-auth
password include password-auth
session required pam_selinux.so close
session required pam_loginuid.so
session required pam_selinux.so open env_params
session optional pam_keyinit.so force revoke
session include password-auth
session include postlogin
EOF
# 4. 临时关闭SELinux
setenforce 0
# 5. 验证配置
echo "验证SSH配置..."
if sshd -t; then
echo "✓ 配置验证通过"
else
echo "✗ 配置验证失败"
exit 1
fi
# 6. 重启服务
systemctl restart sshd
# 7. 显示生效配置
echo ""
echo "=== 生效的配置 ==="
sshd -T | grep -E "passwordauthentication|usepam|permitrootlogin"
# 8. 检查服务状态
if systemctl is-active --quiet sshd; then
echo ""
echo "✓ SSH服务运行正常"
echo ""
echo "=== 修复完成 ==="
echo "现在请测试SSH连接:"
echo "ssh -o PreferredAuthentications=password root@0.0.0.0"
else
echo "✗ SSH服务启动失败"
journalctl -u sshd -n 20
fi