简介
现在很多场景都会用到rsync去备份文件,默认情况下,执行rsync命令是需要输入密码的,如果写shell脚本,就不太方便,所以这里就配置免密。
环境简介
操作系统版本:CentOS Linux release 7.7.1908 (Core) 主机A:192.168.17.128 主机B:192.168.17.130
在本地服务器生成公钥
在Linux操作系统,要是实现2台主机之间实现免密登录,需要先在本地Linux服务器生成一个公钥,然后将公钥拷贝到远程服务器上,就可以实现远程免密登录了。
1.在192.168.17.128服务器上生成公钥 执行ssh-keygen命令之后,需要输入的选项,可以直接回车
[mysql@192 ~]$ ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/home/mysql/.ssh/id_rsa):
Created directory '/home/mysql/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/mysql/.ssh/id_rsa.
Your public key has been saved in /home/mysql/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:+Ay6O18jexPaARVpDlTZkbz26U9fpDSmSzGjI+YpGu4 mysql@192.168.17.128
The key's randomart image is:
+---[RSA 2048]----+
| ...o*.o |
| . = + |
| = . |
| ... o |
| o.S. .+.+ .|
| . +o .oB + |
| o .oBoo.o o .|
| ..oo*++ o.o ..|
| .E=ooo. ... .|
+----[SHA256]-----+
上面命令执行完毕之后,会在mysql用户目录下,生成一个目录“.ssh”
[mysql@192 ~]$ ls -al|grep -i ssh
drwx------ 2 mysql mysql 38 Sep 5 10:50 .ssh
在.ssh目录下会有2个文件,一个是公钥,一个是私钥
[mysql@192 .ssh]$ ll
total 8
-rw------- 1 mysql mysql 1675 Sep 5 10:50 id_rsa
-rw-r--r-- 1 mysql mysql 402 Sep 5 10:50 id_rsa.pub
上传公钥到远程服务器
现在将192.168.17.128服务器上生成的公钥,上传到192.168.17.130服务器上。
1.执行ssh-copy-id 命令拷贝公钥到远程服务器
[mysql@192 ~]$ ssh-copy-id -i /home/mysql/.ssh/id_rsa.pub mysql@192.168.17.130
/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/home/mysql/.ssh/id_rsa.pub"
The authenticity of host '192.168.17.130 (192.168.17.130)' can't be established.
ECDSA key fingerprint is SHA256:I5mQVkAiPi20DGxpgdJHHiI+BoboH78H5hvxweJdxAc.
ECDSA key fingerprint is MD5:1c:6f:ad:b2:20:9d:5f:0e:7f:96:73:17:30:b1:55:1f.
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
mysql@192.168.17.130's password:
Number of key(s) added: 1
Now try logging into the machine, with: "ssh 'mysql@192.168.17.130'"
and check to make sure that only the key(s) you wanted were added.
2.检查远程服务器认证key 检查192.168.17.130服务器用户mysql目录.ssh有认证key
[mysql@oracle11gR2 .ssh]$ pwd
/home/mysql/.ssh
[mysql@oracle11gR2 .ssh]$ ls -l
total 4
-rw-------. 1 mysql mysql 402 Jan 4 05:42 authorized_keys
3.测试远程免密登录
[mysql@192 ~]$ ssh mysql@192.168.17.130
Last login: Mon Jan 4 05:41:57 2021
[mysql@oracle11gR2 ~]$
可以看到已经可以远程免密登录了。
rsync免密传输
上面配置好mysql免密ssh登录之后,就可以rsync免密传输了。
[mysql@192 testdir]$ rsync -avP /home/mysql/testdir/*log mysql@192.168.17.130:/home/mysql/testlog
sending incremental file list
test.log
10 100% 0.00kB/s 0:00:00 (xfr#1, to-chk=0/1)
sent 117 bytes received 35 bytes 304.00 bytes/sec
total size is 10 speedup is 0.07
可以看到已经不需要输入密码了。