$ErrorActionPreference = "Stop"
$KeyPath = "$env:USERPROFILE\.ssh\id_ed25519"
if (-not (Test-Path $KeyPath)) {
Write-Host "正在生成密钥..." -ForegroundColor Yellow
# -N "" 表示无密码,为了极致快;如需密码去掉 -N "" 即可
ssh-keygen -t ed25519 -f $KeyPath -C "windows_auto_key" -N ""
Write-Host "✅ 检测到已有密钥,准备复用" -ForegroundColor Green
# 2. 读取公钥(核心:内存清洗格式,防止乱码)
$Pub = (Get-Content "$KeyPath.pub" -Raw).Trim()
Write-Host "`n请输入 VPS 连接信息:" -ForegroundColor Cyan
$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 $TargetArgs "mkdir -p ~/.ssh && echo '$Pub' >> ~/.ssh/authorized_keys && chmod 700 ~/.ssh && chmod 600 ~/.ssh/authorized_keys"
Write-Host "`n🎉 配置成功!" -ForegroundColor Green
Write-Host "请尝试直接登录: ssh $RawInput" -ForegroundColor Gray