ctyunos-centos等操作系统启用root用户的SSH密码登录

发布于:2025-08-28 ⋅ 阅读:(18) ⋅ 点赞:(0)
#!/bin/bash

# 脚本名称: enable_root_ssh_password.sh
# 描述: 启用root用户的SSH密码登录(安全风险高!)
# 用法: sudo bash enable_root_ssh_password.sh

set -e  # 遇到错误立即退出

echo "⚠️  安全警告:此操作将允许root通过密码SSH登录,存在安全风险!"
read -p "是否继续?(y/N): " confirm

if [[ ! "$confirm" =~ ^[Yy]$ ]]; then
    echo "操作已取消。"
    exit 1
fi

# 备份原始配置文件
SSH_CONFIG="/etc/ssh/sshd_config"
BACKUP_FILE="/etc/ssh/sshd_config.backup.$(date +%Y%m%d_%H%M%S)"

if [ -f "$SSH_CONFIG" ]; then
    cp "$SSH_CONFIG" "$BACKUP_FILE"
    echo "✅ 已备份配置文件到: $BACKUP_FILE"
else
    echo "❌ SSH配置文件不存在: $SSH_CONFIG"
    exit 1
fi

# 修改SSH配置
echo "🔧 修改SSH配置..."

# 确保PermitRootLogin设置为yes
if grep -q "^#*PermitRootLogin" "$SSH_CONFIG"; then
    sed -i 's/^#*PermitRootLogin.*/PermitRootLogin yes/' "$SSH_CONFIG"
else
    echo "PermitRootLogin yes" >> "$SSH_CONFIG"
fi

# 确保PasswordAuthentication设置为yes
if grep -q "^#*PasswordAuthentication" "$SSH_CONFIG"; then
    sed -i 's/^#*PasswordAuthentication.*/PasswordAuthentication yes/' "$SSH_CONFIG"
else
    echo "PasswordAuthentication yes" >> "$SSH_CONFIG"
fi

# 确保PubkeyAuthentication设置为yes(保持密钥登录可用)
if grep -q "^#*PubkeyAuthentication" "$SSH_CONFIG"; then
    sed -i 's/^#*PubkeyAuthentication.*/PubkeyAuthentication yes/' "$SSH_CONFIG"
else
    echo "PubkeyAuthentication yes" >> "$SSH_CONFIG"
fi

echo "✅ SSH配置修改完成"

# 重启SSH服务
echo "🔄 重启SSH服务..."
if systemctl restart sshd 2>/dev/null; then
    echo "✅ SSH服务重启成功"
elif service ssh restart 2>/dev/null; then
    echo "✅ SSH服务重启成功"
else
    echo "❌ 无法重启SSH服务,请手动执行: systemctl restart sshd 或 service ssh restart"
    exit 1
fi

echo ""
echo "=========================================="
echo "✅ 配置完成!Root密码登录已启用。"
echo "⚠️  安全提醒:"
echo "   1. 确保root密码足够复杂"
echo "   2. 考虑使用fail2ban防止暴力破解"
echo "   3. 建议仍优先使用SSH密钥认证"
echo "   4. 配置文件已备份至: $BACKUP_FILE"
echo "=========================================="

# 显示当前配置状态
echo ""
echo "当前SSH配置状态:"
echo "PermitRootLogin: $(grep "^PermitRootLogin" "$SSH_CONFIG" || echo "未设置")"
echo "PasswordAuthentication: $(grep "^PasswordAuthentication" "$SSH_CONFIG" || echo "未设置")"

使用说明

  1. 保存脚本:将上述内容保存为 enable_root_ssh_password.sh

  2. 赋予执行权限

    bash

    chmod +x enable_root_ssh_password.sh
  3. 以root权限运行

    bash

    sudo bash enable_root_ssh_password.sh
  4. 确认操作:脚本会提示确认,输入 y 继续