Menu Home

Centos8 SSH密钥登录

SSH是一种加密的网络协议,旨在用于客户端和服务器之间的安全连接。常用的SSH身份验证机制有两种,基于账号密码的机制和基于公钥机制。本文介绍一下基于公钥机制的登录方式。

在本地创建SSH密钥

在本地机器执行 ls -l ~/.ssh,检查之前是否创建过SSH密钥对。如果如果存在 id_rsa 和 id_rsa.pub两个文件,说明已经创建过,跳过此步骤。

如果没有创建过,执行以下命令:

ssh-keygen

会提示输入文件名,一般直接回车,接受默认文件位置和文件名即可。

Enter file in which to save the key (/home/deployer/.ssh/id_rsa):

接下来会提示输入密码,可以根据自身需要决定是否需要密码:

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

密钥生成完毕,整个交互流程如下。

 ssh-keygen
 Generating public/private rsa key pair.
 Enter file in which to save the key (/home/deployer/.ssh/id_rsa):
 /home/deployer/.ssh/id_rsa already exists.
 Enter passphrase (empty for no passphrase):
 Enter same passphrase again:
 Your identification has been saved in /home/deployer/.ssh/id_rsa.
 Your public key has been saved in /home/deployer/.ssh/id_rsa.pub.
 The key fingerprint is:
 SHA256:KkSe+rCMRDEhxY1VWnknSigFC+S152g9xi2R+3hE7fs deployer@huiye
 The key's randomart image is:
 +---[RSA 3072]----+
 |+=oBooo.         |
 |o..+o+ + .      | | +.oo= + +       | |  oo.* .        |
 | . o+O oS.       |
 |. .o. *.  .      |
 | .o …o .       |
 |.o + ..   .      |
 |. o .      E     |
 +----[SHA256]-----+

拷贝本机的SSH公钥到远程服务器

可以使用命令 scp 将本地生成的SSH公钥拷贝到远程服务器,执行以下命令,并输入登录密码。

scp /path/to/id_rsa.pub username@remote_ip:~/

SSH登录到远程服务器,在用户目录下,可以看到公钥文件 id_rsa.pub。

配置SSH密钥登录

登录远程服务器,在用户目录下,创建文件 ~/.ssh/authorized_keys:

mkdir ~/.ssh && chmod 700 ~/.ssh
touch ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys

把之前上传的公钥文件的内容,写入 ~/.ssh/authorized_keys

cat id_rsa.pub >> ~/.ssh/authorized_keys

检查 /etc/ssh/sshd_config 的配置项 PubkeyAuthentication 是否为 yes。如果不是,修改为yes。

PubkeyAuthentication yes

还可以修改 PasswordAuthentication,禁用密码登录

PasswordAuthentication no

修改配置完毕,重启SSH服务,使配置生效。

sudo systemctl restart sshd

至此,使用SSH密钥登录远程服务器的配置已完成。

额外配置

一般我们会执行类似 ssh root@remote_ip 的命令来登录登录远程服务器。IP地址不容易忘记,我们可以使用别名的方式来代替。

在本机创建文件 ~/.ssh/config,并按以下格式写入配置:

Host example_server              // 别名
     HostName 8.8.8.8            // IP
     Port 22                     // 端口
     User root                   // 用户名
     ServerAliveInterval 30
     ServerAliveCountMax 5

Host、HostName、Port、User,分别替换成实际的信息。ServerAliveInterval 和 ServerAliveCountMax 适用于保持SSH链接会话的。

配置完成后,就可以通过执行以下命令登录远程服务器了,这个比使用IP方便多了,特别是管理多台服务器的时候。

ssh example_server

Categories: Linux

Tagged as:

muzi