Skip to main content

Windows 配置 ssh 免密登录

· 3 min read
therainisme

我真的不想再输入 ssh 的密码了!

配置过程

  1. 在本地系统执行 ssh-keygen -t rsa 命令,生成公私钥文件
PS C:\Users\therainisme> ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (C:\Users\therainisme/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in C:\Users\therainisme/.ssh/id_rsa.
Your public key has been saved in C:\Users\therainisme/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:sU/T++VmVOCTaFccDVC06y4T9y3J5p6OR2a63NwHh0U 13713@Therainisme-Laptop
The key's randomart image is:
| .+++o|
| ..E|
| . o.= |
| o .o =.o|
| S o....+.|
| o ..oB o|
| . .O.*o|
| .+**=*|
| +XX++|
+----[SHA256]-----+

如果有回车直接回车即可,其中 C:\Users\therainisme/.ssh/id_rsa.pub 存放的是公钥文件,C:\Users\therainisme/.ssh/id_rsa 存放的是私钥文件。

  1. 本地机器执行命令:ssh-copy-id -i <公钥文件路径> root@<服务器ip>, 将公钥文件传输的远程机器,并生效。(需要输入远程服务器的密码)
PS C:\Users\therainisme> ssh-copy-id -i C:\Users\therainisme/.ssh/id_rsa.pub root@<服务器ip>

遇到的问题及解决方案

  1. 上传公钥文件时,无法将“ssh-copy-id”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。
PS C:\Users\therainisme> ssh-copy-id -i C:\Users\therainisme/.ssh/id_rsa.pub root@<服务器ip>
ssh-copy-id : 无法将“ssh-copy-id”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保路径正确,然后再试一次。
所在位置 行:1 字符: 1
+ ssh-copy-id -i C:\Users\therainisme/.ssh/id_rsa.pub root@<服务器ip> ...
+ ~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (ssh-copy-id:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException

解决方案:在 PowerShell 中执行以下代码

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. 另一种补救的方式(手动)

将主机的公钥(id_rsa.pub)复制下来,粘贴到服务器的 .ssh/authorized_keys 文件中(追加一行)。