ssh 密钥登陆服务器

1 minute read

Published:

首先进行 ssh 设置密钥,然后在本地配置 ssh config 文件实现快捷登陆。

ssh 设置密钥

1. 在服务器上制作密钥对

首先在服务器上制作密钥对,执行以下命令:

[root@host ~]$ ssh-keygen  <== 建立密钥对
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): <== 按 Enter
Created directory '/root/.ssh'.
Enter passphrase (empty for no passphrase): <== 输入密钥锁码,或直接按 Enter 留空
Enter same passphrase again: <== 再输入一遍密钥锁码
Your identification has been saved in /root/.ssh/id_rsa. <== 私钥
Your public key has been saved in /root/.ssh/id_rsa.pub. <== 公钥
The key fingerprint is:
0f:d3:e7:1a:1c:bd:5c:03:f1:19:f1:22:df:9b:cc:08 root@host

密钥锁码在使用私钥时必须输入,这样就可以保护私钥不被盗用。当然,也可以留空实现无密码登录。

现在,在 root 用户的家目录中生成了一个 .ssh 的隐藏目录,内含两个密钥文件。id_rsa 为私钥,id_rsa.pub 为公钥。

2. 在服务器上安装公钥

键入以下命令,在服务器上安装公钥:

[root@host ~]$ cd .ssh
[root@host .ssh]$ cat id_rsa.pub >> authorized_keys

如此便完成了公钥的安装。为了确保连接成功,请保证以下文件权限正确:

[root@host .ssh]$ chmod 600 authorized_keys
[root@host .ssh]$ chmod 700 ~/.ssh

# 一个玄学问题:~/.ssh 下的 .. 目录权限需要是 755,否则无法登陆(应该是用户目录的权限)
[root@host ~]$ cd ~/.ssh
[root@host ~]$ chmod 755 ..

3. 在服务器上设置 ssh 打开密钥登录功能

编辑 /etc/ssh/sshd_config 文件

vim /etc/ssh/sshd_config

进行如下设置:

RSAAuthentication yes
PubkeyAuthentication yes

另外,请留意 root 用户能否通过 SSH 登录:

PermitRootLogin yes

当你完成全部设置,并以密钥方式登录成功后,再禁用密码登录:

PasswordAuthentication no

最后,重启 SSH 服务:

[root@host .ssh]$ service sshd restart

4. 将私钥下载到客户端

使用 FTP 工具将私钥文件 id_rsa 下载到客户端机器上,便可以在 ssh 客户端工具中使用私钥文件登陆你的服务器账户啦。

5. 其他

制作密钥对的过程其实在服务器或者客户端上制作都可以,只要最后将公钥放在服务器,私钥放在客户端即可,其次如果为了便捷无密码登陆,在制作密钥对时可以不输入密钥锁码。

ssh 配置 config

这部分是给希望直接使用 terminal 和 vscode 远程快捷 ssh 连接服务器使用的,不需要用到 ssh 客户端工具。

1. 在客户端上编辑 ssh 的 config 文件

编辑 ~/.ssh/config 文件

vim ~/.ssh/config

2. 配置 ssh 服务器

Host 为别名
  HostName 为IP
  Port 为端口
  User 为用户名
  IdentityFile 为私钥

例如:

Host best1
  HostName 10.111.111.111
  Port 22
  User abc1
  IdentityFile ~/.ssh/id_rsa1
  
Host best2
  HostName 10.222.222.222
  Port 22
  User abc2
  IdentityFile ~/.ssh/id_rsa2

3. 快捷登陆 ssh 服务器

配置好 ssh 服务器之后便可以在 terminal 中使用 ssh 别名 快捷登陆服务器,例如:

ssh best1

参考资料及致谢

设置 SSH 通过密钥登录

ssh配置config快速登录服务器