转载学习,原文见博客:https://blog.csdn.net/dragon_0505/article/details/142446655

二、免密登录服务器

  1. 创建 SSH 密钥的公钥和私钥
    首先,需要在本地生成一对 SSH 密钥。公钥将被放置在远程服务器上,而私钥保存在本地,用于认证登录。

1.1 生成 SSH 密钥对
打开命令行终端(Windows 用户可以使用 Git Bash、PowerShell 或 Windows Subsystem for Linux,Linux/Mac 用户使用终端),运行以下命令来生成 RSA 密钥对:

ssh-keygen -t rsa -C "your_email@example.com"

-t rsa:指定生成 RSA 类型的密钥对。
-C “your_email@example.com”:为密钥添加注释,通常是你的邮箱地址,方便识别。

1.2 输入密钥存储位置
系统会提示你选择存储私钥的位置。默认存储在 ~/.ssh/id_rsa,直接按 Enter 使用默认路径:

Generating public/private rsa key pair.
Enter file in which to save the key (/home/your_user/.ssh/id_rsa):

1.3 设置密码(可选)
系统会询问你是否为私钥设置密码短语,可以选择设置以增加安全性。如果不需要,直接按 Enter 跳过:

Enter passphrase (empty for no passphrase):
Enter same passphrase again:

完成后,你会在终端看到类似以下的输出,表示密钥已经成功生成:

Your identification has been saved in /home/your_user/.ssh/id_rsa.
Your public key has been saved in /home/your_user/.ssh/id_rsa.pub.

现在你有了一个私钥文件 id_rsa 和一个公钥文件 id_rsa.pub。

  1. 发送公钥到远程服务器
    将生成的公钥文件发送到远程服务器的 ~/.ssh/authorized_keys 文件中,允许你通过私钥登录远程服务器。

2.1 使用 ssh-copy-id 将公钥传到服务器
执行以下命令,将你的公钥复制到服务器(-p 参数指定端口号,默认为 22):

ssh-copy-id -p 22 root@xxxx.com

2.2 过程说明
首次运行 ssh-copy-id 时,需要输入服务器的密码来完成公钥的传输:

root@xxxx.com's password:

输入密码后,ssh-copy-id 会将公钥上传到服务器的 ~/.ssh/authorized_keys 文件中。如果成功,你会看到类似以下输出:

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh -p 12803 root@xxxx.com"
and check to make sure that only the key(s) you wanted were added.
  1. 验证无密码登录
    你现在应该能够通过 SSH 无需密码直接登录到远程服务器。使用以下命令登录:
ssh -p 12803 root@xxxx.com

如果一切正常,你将无需输入密码,直接登录到远程服务器。

三、vscode免密登录服务器

3.1 选择 config 文件
选择本地用户目录的 ~/.ssh/config 文件,用于存储 SSH 连接的配置信息。

3.2 编辑 config 文件
VS Code 会自动打开并编辑 ~/.ssh/config 文件。确保该文件格式正确,并添加如下配置:

Host myserver
    HostName xxxx.com
    User root
    Port 12803
    IdentityFile ~/.ssh/id_rsa

Host myserver:自定义的名称,你可以用它在后续的 Remote-SSH 界面中快捷选择服务器。
HostName:服务器的 IP 地址或域名。
User:远程服务器的用户名。
Port:SSH 连接的端口号。
IdentityFile:本地私钥文件路径,确保你已经生成了密钥对并进行了免密登录配置。

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐