出于安全考虑,通常我们会将服务器的密码连接关闭,仅通过ssh密钥对的方式连接,SSH密钥由一个公钥和一个私钥组成一对,在本地机器生成公钥和私钥后,将公钥放到服务器,而私钥作为连接服务器的钥匙。
首先,我们需要创建一个密钥对。我们尝试进入到本机的用户目录下的.ssh
文件夹下
cd ~/.ssh
如果提示-bash: cd: .ssh: No such file or directory
没有该文件夹,则说明还没有创建过密钥对,我们使用如下命令创建:
vien@x-xlarge:~$ ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/home/vien/.ssh/id_rsa):
Created directory '/home/vien/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/vien/.ssh/id_rsa.
Your public key has been saved in /home/vien/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:5Xlg2BvBAgw8CQDD8i1c98uPXMEBthkPi6hC1KMaueU vien@x-xlarge
The key's randomart image is:
+---[RSA 2048]----+
|*ooo.+*o .. |
|oo +=ooBoo.. |
|.=ooo+oooo* |
|+o= . ++ = |
|+= . So+ . |
|+ E . o . |
| . = |
| o . |
| |
+----[SHA256]-----+
创建之后,我们再进入.ssh
文件夹:
cd ~/.ssh
发现有以下内容 id_rsa
和 id_rsa.pub
,这便是私钥和公钥了,我们使用如下命令将公钥发送给服务器:
ssh-copy-id vien@124.70.181.212
其中@
前是服务器用户名,@
后是服务器地址,并且后续需要输入密码,打印如下:
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/Users/vien/.ssh/id_rsa.pub"
/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
vien@124.70.181.212's password:
Number of key(s) added: 1
Now try logging into the machine, with: "ssh 'vien@124.70.181.212'"
and check to make sure that only the key(s) you wanted were added.
如此这般便可以通过ssh密钥对直接连接了。
需要修改服务器的这个配置文件
sudo vim /etc/ssh/sshd_config
找到如下内容:
# PasswordAuthentication yes
去掉 #
注释,并且把yes改为no,再确定一下ssh密钥连接方式是打开的,找到如下内容:
PubkeyAuthentication yes
确保是关闭注释,并且设置为yes的,然后重启ssh
服务即可
service sshd restart
viencoding.com版权所有,允许转载,但转载请注明出处和原文链接: https://viencoding.com/article/284