有时候我们需要在Linux系统之间互相传输文件,正常登录系统是需要输入密码,但是在自动化执行的时候如果需要手动输入密码就比较麻烦了,如何实现无需密码,但是又保证系统的安全呢?这就使用到了密钥登录。
环境说明:
两台Linux(CentOS 6.7)系统: balichos 192.168.171.50 balichvm 192.168.171.51
1)、分别在balichos和balichvm都安装openssh-clients,可以使用
yuminstall openssh-clients.
2)、分别在balichos和balichvm上修改/etc/hosts的文件,加入balichos和balichvm对应的ip如下:
192.168.171.50 balichos 192.168.171.51 balichvm
3)、使用ssh-keygen生成公钥和私钥,这一步的操作分别在balichos和balichvm两台主机上操作。
# ssh-keygen -t rsa #-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 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: 96:09:8b:c7:ec:6a:f5:40:52:2f:d3:e3:e8:05:ed:21root@balichOS.org The key's randomart image is: +--[ RSA 2048]----+ | | | . | | ..+ | | .+Eo*o | | .o=OSo | | o+.+ | | o.+ | | ... . | | .. | +-----------------+
刚刚的操作也同样在balichvm上操作。
4)、把需要在登录的系统上加入自己的公钥,用自己的私钥作为连接。操作如下:
在balichos上,拷贝公钥到balichvm
# ssh-copy-id root@balichvm
在balichvm上,拷贝公钥到balichos
# ssh-copy-id root@balichos
拷贝公钥到对方的主机上,需要输入密码;
5)分别在balichos和balichvm测试连接。
[root@balichOS ~]# ssh balichvm Last login: Tue Oct 27 21:14:47 2015 frombalichos
[root@balichvm ~]# ssh balichos Last login: Wed Oct 28 05:53:07 2015 frombalichvm
需要注意的问题:
在用户root/.ssh目录下,要保留私钥id_rsa,如果没有这个文件,是不能登录到对方的机器的;
假如需要使用诸如putty、xshell登录系统,需要把私钥id_rsa拷贝出来,在用户验证身份指定私钥id_rsa的文件;
如有多对密钥,authorized_keys里面的公钥的内容追加进去而不是覆盖。
基本的思路就是,公钥存放在需要被连接的机器上,私钥存放在连接的客户端上。私钥是用来解密的。