因为服务器所在不同,所以有两种方式:
一、云上
在云上,可以在创建服务器时,设置通过密钥登陆,它会自动生成密钥,下载下来的密钥,直接保存使用就可以了
二、在服务器上自己生成
[root@localhost ~]# ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
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:
99:46:6d:14:b1:92:9c:48🆎d8:d7:3c:02:fd:12:8a root@localhost.localdomain
The key’s randomart image is:
±-[ RSA 2048]----+
| . +o |
| o + = . |
| . = * + |
| + + * = |
| E + + S |
| . + . |
| |
| |
| |
±----------------+
注:此时在/root/.ssh/目录下生成了2个文件,id_rsa为私钥,id_rsa.pub为公钥。私钥自己下载到本地电脑妥善保存(丢了服务器可就没法再登陆了),
为安全,建议删除服务器端的私钥。公钥则可以任意公开。
[root@localhost ~]# cat /root/.ssh/id_rsa.pub >> /root/.ssh/authorized_keys
三、修改sshd配置(不管是在云上生成,还是自己生成都需要做这一步)
#vim /etc/ssh/sshd_config
RSAAuthentication yes
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys
#AuthorizedKeysCommand none
#AuthorizedKeysCommandRunAs nobody
#默认PasswordAuthentication 为yes,即允许密码登录,改为no后,禁止密码登录
PasswordAuthentication no
PermitEmptyPasswords no
然后重启sshd
[root@localhost ~]# systemctl restart sshd.service
下载id_rsa 或者云上 pem 文件到本地,直接可以登录,切记,密钥登陆,不需要密码,输入密码,会出错,除非在创建密钥的时候输入了密码