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_rsa
、id_rsa.pub
存在,则说明该机器上之前已经生成了 SSH 密钥,可以选择继续使用该密钥或重新生成新密钥。
2. 重新生成密钥
若选择重新生成密钥,则先备份旧密钥(如有需要),再使用以下命令:
> ssh-keygen -t rsa -b 4096 -C "your_email@domain.com"
之后连按 4 次回车,表示采用默认设置,生成密钥:
最后确认已经生成密钥文件id_rsa
、id_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-1
、centos-2
:
> ssh root@centos-1
> ssh root@centos-2
在其他两台主机
centos-1
、centos-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 # 重启服务后生效