Linux 云服务器 VPS 通常使用 SSH 连接进行运维和配置,多数使用root和密码,或SSH密钥对。
密钥对 分为公钥和私钥,公钥存储在服务器,私钥保持在我们的客户端电脑中,下表是现有加密算法介绍:
AlgorithmPublic keyPrivate keyED25519 (preferred)id_ed25519.pubid_ed25519RSA (at least 2048-bit key size)id_rsa.pubid_rsaDSA (deprecated)id_dsa.pubid_dsaECDSAid_ecdsa.pubid_ecdsa
一,登录服务器,使用 OpenSSH 创建 SSH密钥;
1,我们在这里使用 ED25519算法,使用SSH工具 Xshell ,和 root用户登录服务器,输入以下命令查看 OpenSSH版本:
ssh -V
返回值:
OpenSSH_8.9p1 Ubuntu-3, OpenSSL 3.0.2 15 Mar 2022
2,输入以下命令,替换成自己的邮箱:
ssh-keygen -t ed25519 -C “[email protected]”
3,返回以下信息确认密钥的默认保存位置:
Generating public/private ed25519 key pair.
Enter file in which to save the key (/root/.ssh/id_ed25519):
4,按ENTER键,返回以下信息,提示输入SSH密钥对的密码,如果这里创建了密钥,以后使用这组密钥对还是会要求我们输入密码,默认按确认键留空不添加:
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
5,按下ENTER,提示密钥已经创建成功,保持在如下位置:
Your identification has been saved in /root/.ssh/id_ed25519.
Your public key has been saved in /root/.ssh/id_ed25519.pub.
The key fingerprint is:
SHA256:qx6prR4Zo+VU7Fl8yivXzzzzzzzzJ/9NRnPbrC20w7g [email protected]
The key’s randomart image is:
+–[ED25519 256]–+
| |
| o . |
| o B o + . |
| B + + o + |
| = = S o o o |
| = + = O + + |
| . + B B = * . |
| = O + o |
| .+o=.. E . |
+—-[SHA256]—–+
6,查看 /root/.ssh/ 目录(被隐藏,输入路径即可),共3个文件(authorized_keys,id_ed25519,id_ed25519.pub),下载SSH密钥到本地电脑,备份,备用。
二,将 SSH公钥 添加到服务器并登录
将生成的 SSH密钥中的公钥 添加到你的服务器,理论上这适用于你的每一台服务器。
1,使用 ssh-copy-id 命令,将公钥文件 id_ed25519.pub 导入到 authorized_keys,-i [path to public key]指定公钥目录,指定用户名和服务器 IP 地址(或域名),例如 192.0.2.123 ,root 用户:
ssh-copy-id -i ~/.ssh/id_ed25519.pub [email protected]
2,返回信息,确认即可:
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: “/root/.ssh/id_ed25519.pub”
The authenticity of host ‘111.111.111.111 (111.111.111.111)’ can’t be established.
ED25519 key fingerprint is SHA256:n8sd62hdG5G9ASH282F8g29jxuL2YE1Ld0gAGdZul2E.
This key is not known by any other names
Are you sure you want to continue connecting (yes/no/[fingerprint])?
3,提示输入root用户的密码,输入后回车确认。
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed — if you are prompted now it is to install the new keys
[email protected]’s password:
4,返回添加成功:
Number of key(s) added: 1
Now try logging into the machine, with: “ssh ‘[email protected]'”
and check to make sure that only the key(s) you wanted were added.
5,重启服务器,将SSH私钥导入到 Xshell,使用SSH密钥方式登录服务器:
Xshell SSH密钥 登录
三,删除 SSH 密钥,不再使用密钥登录
找到 /root/.ssh/ 目录下的 authorized_keys 文件,删除前面配置的密钥这一行即可。
TagsLinux SSH密钥