Windows配置免密登录Linux服务器

Windows配置免密登录Linux服务器与Linux服务器类似,主要分为以下几步:

1、生成Windows对应用户的公私钥文件
打开cmd,进入用户目录:C:\Users\whwtr,执行ssh-keygen -t rsa命令

C:\Users\whwtr>ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (C:\Users\whwtr/.ssh/id_rsa):
Created directory 'C:\Users\whwtr/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in C:\Users\whwtr/.ssh/id_rsa.
Your public key has been saved in C:\Users\whwtr/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:FSqxxx1FUeT+XfWcbGYexxxQkzVA0Exxx0bQLWBxxxY whwtr@LAPTOP-NH51ES2C
The key's randomart image is:
+---[RSA 3072]----+
|      .oo +==o.o.|
|     . o . o.o =.|
|    . + o o.+ O o|
|   o + o ..o o.B*|
|  . . o S   o oO=|
|     o   . o o= .|
|    .     . +  . |
|             o   |
|            .    |
+----[SHA256]-----+

C:\Users\whwtr>

然后可进入目录C:\Users\whwtr\.ssh查看生成的公私钥。

2、将Windows用户公钥内容追加至要连接的Linux服务器对应的authorized_keys文件
cat id_rsa.pub(Windows)内容 >> authorized_keys(Linux服务器)

然后执行以下授权:
chmod 600 ~/.ssh/authorized_keys

3、打开cmd测试ssh连接
如下所示,即可正常连接至Linux服务器。

C:\Users\whwtr>ssh -p22 business@39.xx.xx.xx
The authenticity of host '39.xx.xx.xx (39.xx.xx.xx)' can't be established.
ECDSA key fingerprint is SHA256:xxxZwxxxt52YlxxxGlap7YN+s4djxxL24bjc/hxx7+4.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '39.xx.xx.xx' (ECDSA) to the list of known hosts.
Last login: Sun Aug 14 00:38:37 2022

Welcome to Alibaba Cloud Elastic Compute Service !

[business@iZ2zegxxxk4ky0d9wxdwriZ ~]$
[business@iZ2zegxxxk4ky0d9wxdwriZ ~]$
[business@iZ2zegxxxk4ky0d9wxdwriZ ~]$ whoami
business
[business@iZ2zegxxxk4ky0d9wxdwriZ ~]$ ls
[business@iZ2zegxxxk4ky0d9wxdwriZ ~]$ exit
logout
Connection to 39.xx.xx.xx closed.

注意:
如果私钥文件以-----BEGIN OPENSSH PRIVATE KEY-----开头,则在Windows搭建的Jenkins远程ssh连接Linux服务器时可能会报以下错误:

jenkins.plugins.publish_over.BapPublisherException: Failed to add SSH key. Message [invalid privatekey: [B@3bb6a780]

错误原因:ssh版本过高导致

解决方法:
Windows执行命令:ssh-keygen -m PEM -t rsa -b 4096
重新生成公私钥,发现私钥文件开头变为:-----BEGIN RSA PRIVATE KEY----- ,然后将新生成的公钥配置到Linux服务器的authorized_keys即可。

添加新评论