环境准备:linux centos7
- 生成密钥
[root@localhost ~]# 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: SHA256:odHbpUMmxCFMIb6gFrbQjGV9sReH8UQLV9jIm571ytk root@localhost The key's randomart image is: +---[RSA 2048]----+ | o..o=+**==. | | * ...o=oB+.. | |oo+ ..o = =o. | |o.o. . + Boo. | |.o . . S.+o . | |. o. . | | . + | | + E | | | +----[SHA256]-----+
2.查看公钥和私钥
[root@localhost ~]# cd ~/.ssh/ [root@localhost .ssh]# ls id_rsa id_rsa.pub [root@localhost .ssh]#
3.使用命令免密登录本机
[root@localhost .ssh]# cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys
结果
[root@localhost .ssh]# ssh 172.17.91.13 The authenticity of host '172.17.91.13 (172.17.91.13)' can't be established. ECDSA key fingerprint is SHA256:odchomQ9i840MAnHy6vDujvpPHuQopkxjKQUsjvuXHo. ECDSA key fingerprint is MD5:df:01:da:6c:e3:35:53:4b:16:56:de:c3:21:1c:60:af. Are you sure you want to continue connecting (yes/no)? yes Warning: Permanently added '172.17.91.13' (ECDSA) to the list of known hosts. Last login: Fri Feb 26 09:40:11 2021 from 172.17.91.1 [root@localhost ~]#
4.将公钥传到另一台服务器上
[root@localhost ~]# scp ~/.ssh/id_rsa.pub root@172.17.91.3:/opt The authenticity of host '172.17.91.3 (172.17.91.3)' can't be established. ECDSA key fingerprint is SHA256:HWh6bbsvT42I2Nev+w2I7b+dT6g4Atjx7hoskB365Kk. ECDSA key fingerprint is MD5:f7:bf:5f:b5:b3:3c:f4:df:b2:e4:68:9d:58:e8:af:74. Are you sure you want to continue connecting (yes/no)? yes Warning: Permanently added '172.17.91.3' (ECDSA) to the list of known hosts. root@172.17.91.3's password: id_rsa.pub 100% 396 360.4KB/s 00:00 [root@localhost ~]#
查看172.17.91.3的opt目录
[root@localhost ~]# cd /opt/ [root@localhost opt]# ls d.txt id_rsa.pub mysql.sh nginx-1.18.0 nginx-1.18.0.tar.gz [root@localhost opt]#
在172.17.91.3的服务器下执行
[root@localhost .ssh]# cat /opt/id_rsa.pub >> ~/.ssh/authorized_keys [root@localhost .ssh]#
由此免密登录成功了!!! nginx-1.18.0.tar.gz是我们172.17.91.3的东西!!!
[root@localhost ~]# ssh 172.17.91.3 Last login: Fri Feb 26 09:40:22 2021 from pc-201811091422.mshome.net [root@localhost ~]# cd /opt/ [root@localhost opt]# ls d.txt id_rsa.pub mysql.sh nginx-1.18.0 nginx-1.18.0.tar.gz [root@localhost opt]#