写这篇文章的起因是我要使用 rsync下载远程服务器的文件备份
但是每次使用 rsync的时候都要输入密码,非常麻烦,而且我是备份脚本,后台运行的时候不能输入密码
解决方法就是我们使用密钥登录
先来看看原理图
这种方法比较安全,只要保管好私钥 就很安全了
将公钥(pub)发送到你要免密登录的服务器的 /root/.ssh/ 这个目录下
实现
1. 制作密钥对
#在客户端生成密钥和公钥
ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): <== 按 Enter
Created directory '/root/.ssh'.
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:
0f:d3:e7:1a:1c:bd:5c:03:f1:19:f1:22:df:9b:cc:08 root@host
2.发送到需要免密登录的服务器
scp /root/.ssh/id_rsa.pub root@192.168.3.5:/root/.ssh/
3. 在服务器上安装公钥
[root@host ~]$ cd .ssh
[root@host .ssh]$ cat id_rsa.pub >> authorized_keys
公钥文件覆盖下 authorized_keys 这个文件
如此便完成了公钥的安装。为了确保连接成功,请保证以下文件权限正确:
[root@host .ssh]$ chmod 600 authorized_keys
[root@host .ssh]$ chmod 700 ~/.ssh
4. 设置 SSH,打开密钥登录功能
编辑 /etc/ssh/sshd_config 文件,进行如下设置:
RSAAuthentication yes
PubkeyAuthentication yes
另外,请留意 root 用户能否通过 SSH 登录:
PermitRootLogin yes
配置完成之后重启下 SSH服务
这是centos 6的命令
[root@host .ssh]$ service sshd restart
如果你是CentOS 7.X 使用如下命令重启 ssh
systemctl restart sshd
5.测试结果
rsync -av root@192.168.3.5:/root/* ./
[root@localhost ~]# rsync -av root@47.106.67.99:/root/* ./
receiving incremental file listsent 20 bytes received 80 bytes 66.67 bytes/sec
total size is 0 speedup is 0.00
发现没有显示需要输入密码