摘自 How to Setup Passwordless SSH Login | Linuxize

1. 查看已有密钥

> ls -l ~/.ssh/
total 12
-rw-------  1 root root 1679 Apr 11 10:11 id_rsa
-rw-r--r--  1 root root  398 Apr 11 10:11 id_rsa.pub
-rw-r--r--. 1 root root 1736 Apr 11 10:21 known_hosts

若可看到id_rsaid_rsa.pub存在,则说明该机器上之前已经生成了 SSH 密钥,可以选择继续使用该密钥重新生成新密钥

2. 重新生成密钥

若选择重新生成密钥,则先备份旧密钥(如有需要),再使用以下命令:

> ssh-keygen -t rsa -b 4096 -C "your_email@domain.com"

之后连按 4 次回车,表示采用默认设置,生成密钥:

连按 4 次回车,生成密钥文件
连按 4 次回车,生成密钥文件

最后确认已经生成密钥文件id_rsaid_rsa.pub

> ls ~/.ssh/id_*
/root/.ssh/id_rsa  /root/.ssh/id_rsa.pub

3. 将公钥复制到其他主机

使用ssh-copy-id命令将本机的公钥复制到指定主机的authorized_keys文件中

> ssh-copy-id remote_username@server_ip_address

例如现在我有三台 Linux 主机,均已生成 SSH 密钥,主机名如下所示:

  • abelsu7-ubuntu
  • centos-1
  • centos-2

abelsu7-ubuntu为例,执行以下命令:

> ssh-copy-id root@centos-1
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.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
root@centos-1 password: 

Number of key(s) added: 1

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

> ssh-copy-id root@centos-2
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.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
root@centos-2 password: 

Number of key(s) added: 1

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

之后就可以在abelsu7-ubuntu直接通过 SSH 免密登录centos-1centos-2

> ssh root@centos-1

> ssh root@centos-2

在其他两台主机centos-1centos-2上重复以上操作,即可在三台 Linux 主机上互相 SSH 免密登录

另外,如果ssh-copy-id不可用,则可使用以下命令作为替代:

> cat ~/.ssh/id_rsa.pub | ssh remote_username@server_ip_address "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"

4. 禁用 SSH 密码登录(可选)

关于sshd_config的更多配置,可参考 Using the SSH Config File | Linuxize

若要禁用 SSH 密码登录,则需修改sshd_config配置文件

> sudo vim /etc/ssh/sshd_config
...
# 修改如下
PasswordAuthentication no
ChallengeResponseAuthentication no
UsePAM no
...

> sudo systemctl restart sshd # 重启服务后生效

参考文章

  1. How to Set Up SSH Keys on CentOS 7 | Linuxize
  2. How to Setup Passwordless SSH Login | Linuxize
  3. Using the SSH Config File | Linuxize
  4. How to Change the SSH Port in Linux | Linuxize
  5. CentOS 7 如何实现免密登录(三个及三个以上机器)| CSDN

SSH 相关文章收集

  1. 4 Ways to Speed Up SSH Connections in Linux | TecMint
  2. ssh-chat – Make Group/Private Chat with Other Linux Users Over SSH | TecMint
  3. 高级 SSH 速查表 | Linux 中国