做集群部署時,節點之間反覆要輸入密碼是件很折磨人的事。配置基於密鑰的認證之後,登入與遠端執行命令都不再需要密碼。
[root@Ams ~]# ssh-keygen -t rsa Generating public/private rsa key pair. Enter file in which to save the key (/root/.ssh/id_rsa): Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in /root/.ssh/id_rsa. Your public key has been saved in /root/.ssh/id_rsa.pub. The key fingerprint is: 67:37:f3:cb:90:37:b7:83:19:27:e6:85:4e:e9:68:ec root@Ams
passphrase 直接留空,才能实现真正的免密。
[root@Ams ~]# ls .ssh/ id_rsa id_rsa.pub known_hosts
[root@Ams ~]# ssh-copy-id -i .ssh/id_rsa.pub root@192.168.1.117 root@192.168.1.117's password: Now try logging into the machine, with "ssh 'root@192.168.1.117'", and check in: .ssh/authorized_keys to make sure we haven't added extra keys that you weren't expecting.
公鑰會被追加到遠端使用者的 ~/.ssh/authorized_keys 中。
[root@Ams ~]# ssh root@192.168.1.117 Last login: Sun Jul 31 22:56:04 2016 from 192.168.1.115 [root@bluee ~]#
連遠端執行命令也不需要密碼了,這正是集群配置所需要的:
[root@Ams ~]# ssh root@192.168.1.117 'ifconfig' eth0 Link encap:Ethernet HWaddr 00:0C:29:C1:45:55 inet addr:192.168.1.117 Bcast:192.168.1.255 Mask:255.255.255.0 UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 lo Link encap:Local Loopback inet addr:127.0.0.1 Mask:255.0.0.0 UP LOOPBACK RUNNING MTU:65536 Metric:1
補充兩點實務經驗:~/.ssh 權限需為 700、authorized_keys 需為 600,否則 sshd 基於安全考量會拒絕使用密鑰;若 SELinux 為 enforcing,還需 restorescon 還原檔案的安全上下文。