例如:有两台服务器,需要在B上免密码登录A服务器。
A:192.168.1.222
B:192.168.1.211
一、在B服务器上生成公钥和私钥
ssh-keygen -t rsa -b 4096 -C "hasi@163.com"
提示输出路径和密码 ,直接回车就行!
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/zhaohasi/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
生成的公钥私钥在~/.ssh目录下,id_rsa是私钥, id_rsa.pub是公钥
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/zhaohasi/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /Users/zhaohasi/.ssh/id_rsa.
Your public key has been saved in /Users/zhaohasi/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:o06MxebjsViEaI2OJKXZ0s9KCxCs+T9dzNnby/JbIQk zhaohasi@zhaohasideiMac-2.local
The key's randomart image is:
+---[RSA 2048]----+
| |
|. |
|... E |
|.O + o . . |
|O.* o =oSo o . |
|+* o B .=.. . . |
|o + +.O. o . |
| o +.*.+ o... |
| o o.+ o=o |
+----[SHA256]-----+
生成公钥和私钥成功
生成的文件:
➜ ~ cd .ssh
➜ .ssh ll
-rw------- 1 zhaohasi staff 1.8K 8 5 14:12 id_rsa
-rw-r--r-- 1 zhaohasi staff 413B 8 5 14:12 id_rsa.pub
在.ssh目录里,开启 SSH 代理
➜ .ssh eval "$(ssh-agent -s)"
将SSH id_rsa 加入代理中
➜ .ssh ssh-add ~/.ssh/id_rsa
二、登录到A服务器(192.168.1.222)
重复 上面步骤
在A服务器上也生成 ssh 公钥和私钥, 同时开启ssh代理 加入代理
三、在A服务器上.ssh目录中 建立authorized_keys文件
[git@localhost .ssh]$ vi authorized_keys
四、将B服务器.ssh 目录中的 id_rsa.pub 公钥 内容拷贝到 A 服务器.ssh 目录中的 authorized_keys 文件中
➜ .ssh cat id_rsa.pub
拷贝加密key
[git@localhost .ssh]$ vi authorized_keys
粘贴到 authorized_keys中
五、修改 authorized_keys 权限
sudo chmod 644 ~/.ssh/authorized_keys
修改修改.ssh目录的权限以及authorized_keys 的权限(这个必须修改,要不然还是需要密码)
sudo chmod 644 ~/.ssh/authorized_keys
sudo chmod 700 ~/.ssh
六、重启SSH 服务
service sshd restart