本篇是系列的第 1 篇,重点把“生成密钥 + 上传公钥”这一步做到一次成功。
二、生成密钥(本地 Windows)
在你的 本地电脑 PowerShell 中执行(推荐使用 ed25519 算法,比 RSA 更快更安全):
ssh-keygen -t ed25519 -C "my-laptop"一路回车即可。
- 关于 Passphrase:
- 回车留空:为了极致的方便,登录完全免密。
- 设置密码:如果你的电脑经常借给别人用,或者担心私钥文件被盗,可以设个密码(双重保险)。
生成后,文件通常在 C:\Users\用户名\.ssh\:
id_ed25519:私钥(保管好!)id_ed25519.pub:公钥(我们要发给 VPS)
三、部署公钥到 VPS(一键直连版)
⚠️ 高能预警:Windows PowerShell 的管道(|)传输文本时,经常会带入 UTF-16 编码或特殊换行符,导致 Linux 服务器识别为乱码,出现“明明配了 Key 却还是要输密码”的经典 Bug。
为了彻底解决这个问题,这里使用懒人一键直连方案。不需要新建脚本文件!直接打开 PowerShell,复制下面这整段代码,一次性粘贴进去按回车即可。
这段代码会自动处理编码,并且支持非标准端口(如 2222)。
& { # --- 配置开始 --- $ErrorActionPreference = "Stop" $KeyPath = "$env:USERPROFILE\.ssh\id_ed25519"
# 1. 检查或生成密钥(如不存在则生成) if (-not (Test-Path $KeyPath)) { Write-Host "正在生成密钥..." -ForegroundColor Yellow # -N "" 表示无密码,为了极致快;如需密码去掉 -N "" 即可 ssh-keygen -t ed25519 -f $KeyPath -C "windows_auto_key" -N "" } else { Write-Host "✅ 检测到已有密钥,准备复用" -ForegroundColor Green }
# 2. 读取公钥(核心:内存清洗格式,防止乱码) $Pub = (Get-Content "$KeyPath.pub" -Raw).Trim()
# 3. 交互输入地址(支持端口) Write-Host "`n请输入 VPS 连接信息:" -ForegroundColor Cyan Write-Host " - 默认端口(22)直接输:[email protected]" -ForegroundColor Gray Write-Host " - 非标准端口请加参数:-p 2222 [email protected]" -ForegroundColor Gray $RawInput = Read-Host "> "
if (-not $RawInput) { Write-Error "地址不能为空"; return }
# 关键处理:按空格分割参数,确保 -p 2222 能被 SSH 正确识别 $TargetArgs = $RawInput -split ' '
Write-Host "`n正在连接服务器上传公钥..." -ForegroundColor Cyan Write-Host "⚠️ 注意:接下来请输入一次服务器的【登录密码】" -ForegroundColor Yellow
# 执行 SSH 组合拳 ssh $TargetArgs "mkdir -p ~/.ssh && echo '$Pub' >> ~/.ssh/authorized_keys && chmod 700 ~/.ssh && chmod 600 ~/.ssh/authorized_keys"
if ($?) { Write-Host "`n🎉 配置成功!" -ForegroundColor Green Write-Host "请尝试直接登录: ssh $RawInput" -ForegroundColor Gray }}