一个快速构建ssh密钥信任登录的小函数
function sshauth { param( [string]$sshname, [string]$publicKeyFile ) if (-not $sshname -or -not $publicKeyFile) { Write-Host "请提供 sshname 和 publicKeyFile 参数。" return } try { $publicKey = Get-Content $publicKeyFile -Raw $publicKey = $publicKey -replace "`r`n", "`n" } catch { Write-Host "无法读取公钥文件: $_" return } try { $sshdir = "ssh $sshname 'mkdir -p .ssh ; chmod 700 ~/.ssh'" Invoke-Expression $sshdir $sshCommand = "ssh $sshname 'echo `"$publicKey`" >> ~/.ssh/authorized_keys'" Invoke-Expression $sshCommand Write-Host "公钥已传递到 $sshname,并添加到其信任列表中。" } catch { Write-Host "无法将公钥传递到 $($sshname): $_" } }
这是我pwsh中的一个常用函数,用于和一台新服务器之间快速构建密钥信任登录,用法也很简单:
ssh [host] [public key]
第一个参数是ssh config里面的host,第二则是生成的密钥对里的公钥,这样就能快速在一台新机器上建立ssh密钥登录。