在多数情况下,处于安全考虑,使用SSH登录到CentOS服务器时,需要提供正确的用户密码方可登录。但在某些特殊情况下,比如后台进程进行远程文件备份时,我们依然采用SSH登录,但此时不希望提供密码就能登录到服务器。最近在做的一个项目就是这样,利用rsync在服务器间进行文件的同步,这时要避免输入密码的情况存在,否则后台备份就会失败。
需求与分析:
两台服务器,机器名和IP分别如下:
■ Server cluster1:192.168.1.201
■ Server cluster2:192.168.1.202
rsync将文件从cluster1同步到cluster2上,要求从cluster1上使用SSH登录到cluster2不需要输入登录用户的账号密码,即建立两台服务器间的信任登录。
配置步骤:
1、在cluster1上生成SSH密钥对【cluster1:root用户】
- # ssh-keygen -t rsa
- Generating public/private rsa key pair.
- Enter file in which to save the key (/root/.ssh/id_rsa):[直接回车]
- Created directory '/root/.ssh'.
- 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:
- 60:bd:db:66:14:1f:e9:22:c2:01:42:16:28:bb:c6:3e root@Cluster1
上述命令为root用户生成一个密钥对:id_rsa(私钥文件)和id_rsa.pub(公钥文件)。默认被保存在/root/.ssh/目录下。
2、将公钥id_rsa.pub文件通过网络复制到cluster1中【cluster1:root用户】
- # cd /root/.ssh/
- # scp id_rsa.pub root@192.168.1.202:/root/.ssh/192.168.1.201
- The authenticity of host '192.168.1.202 (192.168.1.202)' can't be established.
- RSA key fingerprint is da:09:bf:0a:2f:83:d1:17:1a:f7:4c:dd:54:6d:5d:8c.
- Are you sure you want to continue connecting (yes/no)? yes
- Warning: Permanently added '192.168.1.202' (RSA) to the list of known hosts.
- root@192.168.1.202's password:[输入cluster2服务器中root用户的密码]
- id_rsa.pub 100% 395 0.4KB/s 00:00
命令scp id_rsa.pub root@192.168.1.202:/root/.ssh/192.168.1.201的意思是以192.168.1.202的root用户身份登录到192.168.1.202上,将id_rsa.pub文件拷贝到192.168.1.202机器上的/root/.shh/目录下,并将id_rsa.pub重命名192.168.1.201。这样做的好处是进行多台服务器间的信任时,可以以IP来区分公钥文件,不容易混淆。若192.168.1.202上没有/root/.ssh目录,则会自动创建该目录。
3、登录到cluster2服务器上,追加id_rsa.pub公钥文件的内容至authorized_keys中【cluster2:root用户】
- # cd /root/.ssh/
- # ll
- 总计 8
- -rw-r--r-- 1 root root 395 05-31 20:55 192.168.1.201
可以清楚的看到,公钥文件已经复制过来了,并重命名为192.168.1.201。
接下来就将公钥文件里的内容追加到authorized_keys文件中,并更改其文件权限为600:
- # cat 192.168.1.201 >> authorized_keys
- # chmod 600 authorized_keys
4、重启cluster2服务器上的SSH服务:
- # service sshd restart
- 停止 sshd:[确定]
- 启动 sshd:[确定]
5、从cluster1上使用SSH登录到cluster2上,无需输入密码:
- [root@Cluster1 .ssh]# ssh 192.168.1.202
- Last login: Tue May 31 21:05:51 2011 from 192.168.1.100
- [root@Cluster2 ~]#
原理也很简单,在cluster1使用SSH登录到cluster2上时,会携带私钥id_rsa,其对应的公钥我们已经写入cluster2的/root/.ssh/authorized_keys中,这样私钥和公钥匹配了,登录也就不需要密码了,因为cluster2信任cluster1。
另外要注意一点:authorized_keys文件的权限设置为600;如果是为用户root生成了密钥对,authorized_keys文件的属主必须也是root,否则ssh登录时还是要输入密码。这个问题我也搞了好久才搞明白。