使用现有的 SSH 密钥对和 openSSH 连接服务器

使用现有的 SSH 密钥对和 openSSH 连接服务器

我的同事为我提供了一个 SSH 密钥对文件(公钥和私钥文件),用于连接远程 Linux 服务器,该服务器的authorized_keys文件中包含公钥。

我目前正在使用 Windows 10,并且我的机器上已经安装了 openSSH 客户端。

我不确定 SSH 具体如何工作,但我想知道如何让我的 openSSH 客户端知道我拥有的公钥和私钥,并让它使用它们连接到远程服务器。

笔记:我的 openSSH 客户端目前正在使用现有密钥对id_rsa连接我的 Gitlab 帐户。

答案1

最简单的使用方法是使用“ -i”选项来使用你获得的私钥,例如

ssh -i /path/to/private.key [email protected]

从安全角度来看,我会担心您的朋友为您提供了私钥 - 这不是最佳做法。正确的方法是使用您的公钥 (id_rsa.pub),然后给他一份副本,以添加到服务器的 authorized_keys 文件中,同时保持私钥的私密性。除了连接到他要求您连接的服务器之外,您不应该信任他给您的私钥(即使如此,如果合适,您也应该更新 authorized_keys 文件以使用您生成的公钥 - 并在适用的情况下为他提供一个新的公钥)

更多细节:

您通常将密钥放在 (home_directory)/.ssh 中 - 根据手册

 -i identity_file
         Selects a file from which the identity (private key) for public key authentication is read.  The default is ~/.ssh/id_dsa, ~/.ssh/id_ecdsa, ~/.ssh/id_ecdsa_sk,
         ~/.ssh/id_ed25519, ~/.ssh/id_ed25519_sk and ~/.ssh/id_rsa.  Identity files may also be specified on a per-host basis in the configuration file.  It is possible to have multiple
         -i options (and multiple identities specified in configuration files).  If no certificates have been explicitly specified by the CertificateFile directive, ssh will also try to
         load certificate information from the filename obtained by appending -cert.pub to identity filenames.

如果您想自动使用特定于主机的给定密钥对,您可以使用 CertificationFile 指令(我从未使用过这个)或更常见的是创建/添加适当的行到您的 ~/.ssh/config 文件以使用特定于主机的密钥 - 我相信它看起来像这样:

  Host host-nick-name
        Hostname ip.addr.of.host
        User myusername
        IdentityFile /path/to/identity.file
        

答案2

通常在装有 OpenSSH 的 Windows 上,私钥文件需要位于C:\Users\[your username]\.ssh\id_rsa(或 id_ed25519 或 id_ecdsa 或其他)。

话虽如此,如果您想连接到 Windows 上的 SSH 服务器,我建议您使用 PuTTY。使用 puttygen 将密钥转换为 ppk,然后打开 putty.exe。

  • 在连接 -> SSH -> 认证 -> 私钥文件中指定密钥路径进行认证。
  • 在“连接”->“数据”->“自动登录用户名”中指定您的用户名
  • 在会话 -> 主机名 (或 IP 地址) 中指定您的主机名
  • 在“会话”->“已保存的会话”中命名会话,然后单击“保存”按钮
  • 完成所有操作后,点击打开

相关内容