SSH 免密登录配置详解
搞定 SSH 免密其实就三步:生成密钥、分发公钥、验证权限。整个过程无需输入密码,非常适合自动化运维及频繁交互场景。
1. 生成密钥对
先在源服务器上把钥匙做好。运行 ssh-keygen 后连续三次回车即可,默认会生成 RSA 密钥对。
[syncd@VM_121_116_centos .ssh]$ ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/home/syncd/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/syncd/.ssh/id_rsa.
Your public key has been saved in /home/syncd/.ssh/id_rsa.pub.
The key fingerprint is: SHA256:fLvONE5cJvkxA95kyJxygAxXWnwr9GO1zAkZTlhWLnc syncd@VM_121_116_centos
The key's randomart image is:
+---[RSA 2048]----+
| .o.++o=+.
| .oo+B++.
| ...oX*=oE
| ..+=O=.
| So=.B
| o * +
| * .
| = o
| .= |
+----[SHA256]-----+
[syncd@VM_121_116_centos .ssh]$ ll
total 12
-rw------- 1 syncd syncd 1675 Apr 10 15:06 id_rsa
-rw-r--r-- 1 syncd syncd 405 Apr 10 15:06 id_rsa.pub
-rw-r--r-- 1 syncd syncd 346 Apr 10 14:21 known_hosts
这里要注意,私钥 id_rsa 权限必须严格限制,否则后续连接可能会失败。
2. 分发公钥
将生成的公钥推送到目标主机。如果目标机器不是默认的 22 端口,记得加上 -p 参数。
[syncd@VM_121_116_centos .ssh]$ ssh-copy-id -i ~/.ssh/id_rsa.pub [email protected] -p 22522
/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/home/syncd/.ssh/id_rsa.pub"
The authenticity of host '[rjdev.hand-china.com]:22522 ([116.228.77.180]:22522)' can't be established.
ECDSA key fingerprint is SHA256:IR2YBFvxG8WOPIS3GGzL+n3jFHAbjcAEddMfCkkTsdg.
ECDSA key fingerprint is MD5:f5:dd:f8:00:17:f7:da:7a:42:5c:b0:2f:31:bd:d0:5e.
Are you sure you want to continue connecting (yes/no)? yes
/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
[email protected]'s password:
Number of key(s) added: 1
Now try logging into the machine, with: "ssh -p '22522' '[email protected] '" and check to make sure that only the key(s) you wanted were added.
遇到确认提示输 yes 就行,随后输入目标主机的密码完成授权写入。
3. 验证连接
检查目标主机的授权文件是否存在,最后直接测试连接。

