Linux 设置 ssh 免密登陆

设置ssh免密登陆

问题描述

有两台服务器A和B,如何让A通过ssh连接B的时候不用每次都输入密码。

方法

在A机器上用 ssh-keygen 生成私钥和公钥,将生成的公钥复制到B上就可以了。

在A上生成密钥

使用ssh-keygen生成密钥,按提示输入内容,也可以什么都不输入:

$ ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/home/jactor/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/jactor/.ssh/id_rsa.
Your public key has been saved in /home/jactor/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:ws1GX7dSOx2HVyyjNIPWnWJv+SiCaCxpq2nePWYRQ18 jactor@Jactor-D
The key's randomart image is:
+---[RSA 2048]----+
| o . o.|
| . E B =.o|
| . ..o o.*+=o|
| .o+.. ..o+=o|
| oo+S.. ..+o.|
| + =o. . .....|
| . + . . . |
| .o..+ |
| o+..o.. |
+----[SHA256]-----+

可使用 -t 选项指定密钥类型,默认是rsa。

这时会在上面指定的目录下( /home/jactor/.ssh/ )生成两个文件: id_rsaid_rsa.pub

将A机器的公钥复制到B机器

使用 ssh-copy-id 命令将生成的公钥文件复制到B机器:

$ ssh-copy-id root@vmhost03
/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
root@vmhost03's password:

Number of key(s) added: 1

Now try logging into the machine, with: "ssh 'root@vmhost03'"
and check to make sure that only the key(s) you wanted were added.

ssh-copy-id 命令将 id_rsa.pub 的内容复制粘贴到B机器的 /home/$USER/.ssh 目录下(root账户为 /root/.ssh) 的 authorized_keys 文件中,如果没有 authorized_keys 文件则需要先创建。

之后就可以免密登陆B机器了。