SSH 密钥登录配置

安全配置 SSH 密钥登录,修改默认端口,关闭密码登录,提升服务器安全性



生成 SSH 密钥

1. 打开 PowerShell

以管理员身份打开 Windows PowerShell:

  • 右键点击 PowerShell 图标

  • 选择"以管理员身份运行"

2. 生成密钥对

使用以下命令生成 SSH 密钥对:

ssh-keygen -t ed25519 -C "your_email@example.com"

如果 VPS 较老不支持 ed25519,使用 RSA 算法:

ssh-keygen -t rsa -b 4096 -C "your_email@example.com"

3. 设置保存路径

系统会提示输入保存路径:

Enter file in which to save the key (/c/Users/你的用户名/.ssh/id_ed25519):

直接按回车使用默认路径:C:\Users\你的用户名\.ssh\

4. 设置密钥密码

设置密钥的密码(可选,可直接留空):

Enter passphrase (empty for no passphrase):
Enter same passphrase again:

密码设置建议

设置密码会增加安全性,但每次使用密钥时都需要输入密码。如果追求便利性,可以留空。

5. 生成的文件

密钥生成完成后,会在指定目录创建两个文件:

私钥文件

  • id_ed25519

保存在本地计算机,切勿泄露

公钥文件

  • id_ed25519.pub

需要上传到 VPS 服务器

服务器配置

重要警告

在执行以下配置前,请确保:

  • 已成功生成 SSH 密钥对

  • 已备份服务器重要数据

  • 有其他方式访问服务器(如 VNC)以防配置错误

1. 登录 VPS 服务器

使用当前密码登录到您的 VPS:

ssh root@你的VPS_IP

2. 一键配置脚本

在 VPS 上执行以下完整配置脚本:

SSH_PORT=25701

mkdir -p ~/.ssh
chmod 700 ~/.ssh

cat > ~/.ssh/authorized_keys <<'EOF'
你的 id_ed25519.pub 公钥内容粘贴在这里
EOF

chmod 600 ~/.ssh/authorized_keys

SSHD_CONFIG="/etc/ssh/sshd_config"

cp $SSHD_CONFIG ${SSHD_CONFIG}.bak.$(date +%F-%H%M%S)

sed -i "s/^#\?Port .*/Port ${SSH_PORT}/" $SSHD_CONFIG
sed -i "s/^#\?PasswordAuthentication .*/PasswordAuthentication no/" $SSHD_CONFIG
sed -i "s/^#\?PermitRootLogin .*/PermitRootLogin prohibit-password/" $SSHD_CONFIG
sed -i "s/^#\?PubkeyAuthentication .*/PubkeyAuthentication yes/" $SSHD_CONFIG

grep -q "^Port ${SSH_PORT}" $SSHD_CONFIG || echo "Port ${SSH_PORT}" >> $SSHD_CONFIG

if command -v ufw >/dev/null 2>&1; then
  ufw allow ${SSH_PORT}/tcp
  ufw reload
elif command -v firewall-cmd >/dev/null 2>&1; then
  firewall-cmd --permanent --add-port=${SSH_PORT}/tcp
  firewall-cmd --reload
fi

systemctl restart ssh || systemctl restart sshd

重要提示

在执行脚本前,请务必将 你的 id_ed25519.pub 公钥内容粘贴在这里 替换为您的实际公钥内容。

脚本功能说明

脚本执行的操作

步骤

操作

说明

1

设置 SSH 端口

将默认 22 端口改为 25701

2

创建 SSH 目录

创建 .ssh 目录并设置权限

3

添加公钥

将您的公钥添加到 authorized_keys

4

配置 SSH 服务

修改 sshd_config 文件

5

配置防火墙

开放新的 SSH 端口

6

重启 SSH 服务

使配置生效

SSH 配置参数

参数

说明

Port

25701

SSH 服务监听端口

PasswordAuthentication

no

禁用密码登录

PermitRootLogin

prohibit-password

仅允许密钥登录 root

PubkeyAuthentication

yes

启用公钥认证

测试连接

使用新配置连接 VPS

配置完成后,使用以下命令测试连接:

ssh -p 25701 root@你的VPS_IP

如果系统提示输入密钥密码,请输入您在生成密钥时设置的密码。

简化连接配置

为了更方便地连接,可以在本地创建 SSH 配置文件:

nano ~/.ssh/config

添加以下内容:

Host myserver
    HostName 你的VPS_IP
    Port 25701
    User root
    IdentityFile ~/.ssh/id_ed25519

配置完成后,可以使用简化的命令连接:

ssh myserver