step 1 在本机生成密钥对

若主机中未生成过密钥,则执行:

1
ssh-keygen -t rsa

若本机中存在密钥,则会出现如下提示,不需要再次生成。

image-20230829091303048

step 2 上传公钥到服务器

Linux

1
ssh-copy-id -p [port] [username]@[ip]

Windows

windows 需要再PowerShell中进行操作

首先在PowerShell种执行以下代码

1
2
3
4
5
6
7
8
9
function ssh-copy-id([string]$userAtMachine, $args){   
$publicKey = "$ENV:USERPROFILE" + "/.ssh/id_rsa.pub"
if (!(Test-Path "$publicKey")){
Write-Error "ERROR: failed to open ID file '$publicKey': No such file"
}
else {
& cat "$publicKey" | ssh $args $userAtMachine "umask 077; test -d .ssh || mkdir .ssh ; cat >> .ssh/authorized_keys || exit 1"
}
}

然后执行

1
ssh-copy-id -p [port] [username]@[ip]