功能简介

作者注:脚本默认作用于 root 账户。

在日常运维工作中,启用基于 SSH 公钥的认证方式是一种更加安全且推荐的做法。不仅可以提高登录效率,还能有效防止暴力破解密码攻击。

本文通过一个 Bash 脚本,手把手教你如何在 Ubuntu 服务器上启用 SSH 密钥认证,并彻底关闭密码登录。

脚本自动完成以下任务:

✅ 生成 SSH 密钥对(非交互式)
✅ 设置 ~/.ssh/authorized_keys 权限并添加公钥
✅ 配置 /etc/ssh/sshd_config 文件,实现只允许密钥登录
✅ 重启 ssh 服务以使修改生效

脚本内容

创建一个 setup_ssh_key.sh 脚本文件

vim setup_ssh_key.sh

将以下内容保存并执行它即可完成所有配置。

#!/bin/bash

# Step 1: Generate SSH key pair
echo "Generating SSH key pair..."
ssh-keygen -t rsa -b 4090 -N "" -f /root/.ssh/id_rsa

# Step 2: Create authorized_keys file if not exists and set permissions
mkdir -p /root/.ssh
touch /root/.ssh/authorized_keys
chmod 600 /root/.ssh/authorized_keys

# Step 3: Append public key to authorized_keys
cat /root/.ssh/id_rsa.pub >> /root/.ssh/authorized_keys

# Step 4: Configure SSH to use keys for authentication and disable password login
echo "Configuring SSH..."
cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak
cat > /etc/ssh/sshd_config << EOF
# Essential settings
KbdInteractiveAuthentication no
UsePAM yes
X11Forwarding yes
PrintMotd no
AcceptEnv LANG LC_*
Subsystem       sftp    /usr/lib/openssh/sftp-server

# Max authentication attempts
MaxAuthTries 6

# Permit root login via public key only
PermitRootLogin without-password

# Disable password authentication
PasswordAuthentication no

# Key-related settings
PubkeyAcceptedKeyTypes +ssh-rsa
RSAAuthentication yes
PubkeyAuthentication yes

# Ensure only key-based authentication is permitted
AuthenticationMethods publickey
EOF

# Step 5: Restart SSH service
echo "Restarting SSH service..."
systemctl restart sshd

echo "SSH configuration is complete."

执行脚本文件

sh ./setup_ssh_key.sh

注意事项

将id_rsa文件内容 下载到本地-登录使用的密钥文件

vim ~/.ssh/id_rsa

✅ 生成的密钥类型为 RSA,长度 4090 位,适用于大多数客户端。
✅ 若已有密钥文件,请注意备份 ~/.ssh/id_rsaid_rsa.pub
✅ 修改 sshd_config 存在风险,请谨慎操作,建议保留当前终端连接直到验证成功。
✅ 公钥也可复制到其他用户账户,实现多账户免密登录。


作者:admin  创建时间:2025-10-20 15:20
最后编辑:admin  更新时间:2025-10-20 15:23