操作目的
- serverA 和 serverB 都是 root 用户
- serverA ip 为 192.168.1.11
- serverB ip 为 192.168.1.12
-
操作步骤
在 serverA 上执行命令, 生成密钥对,( 如果已生成可以略过 )
更多的创建方式可以参考 https://www.yuque.com/lwmacct/openssh/ssh-keygen
# Linux 当前用户ssh目录生成 (常用)
ssh-keygen -t ed25519 -N '' -f $HOME/.ssh/id_ed25519 -C 'lwmacct'
# ssh-keygen -t ed25519 -N '' -f id_ed25519 -C 'lwmacct'
:::tips
将 serverA 上的公钥, 上传到 serverB 设备上实现免密登录
这个过程,其实就是将 serverA 中的
/root/.ssh/id_rsa.pub
文件文件, 追加到 serverB 的/root/.ssh/authorized_keys
文件中 :::使用 ssh-copy-id
将公钥上传到需要免密登录的主机
ssh-copy-id -f -p 22 root@192.168.1.12
```bash [root@vscode workspace]# ssh-copy-id -f -p 22 root@192.168.1.12 /usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: “/root/.ssh/id_rsa.pub”
Number of key(s) added: 1
Now try logging into the machine, with: “ssh -p ‘22’ ‘root@192.168.1.12’” and check to make sure that only the key(s) you wanted were added.
[root@vscode workspace]#
<a name="msNY2"></a>
# 其他方式
cat ~/.ssh/id_rsa.pub | ssh -p 22 root@192.168.1.12 ‘cat >> ~/.ssh/authorized_keys’
<a name="RCV2a"></a>
# 注意事项
:::tips
另外我们要注意,.ssh目录的权限为700,其下文件authorized_keys和私钥的权限为600。否则会因为权限问题导致无法免密码登录。我们可以看到登陆后会有known_hosts文件生成。
:::
- 直接执行以下命令, 解决文件权限问题
```bash
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys
chmod 600 ~/.ssh/id_rsa
chmod 644 ~/.ssh/id_rsa.pub
1. [useb@serverB ~]$ ls -la .ssh
2. total 24
3. drwx------. 2 useb useb 4096 Jul 27 16:13 .
4. drwx------. 35 useb useb 4096 Aug 24 09:18 ..
5. -rw------- 1 useb useb 796 Aug 24 09:24 authorized_keys
6. -rw------- 1 useb useb 1675 Jul 27 16:09 id_rsa
7. -rw-r--r-- 1 useb useb 397 Jul 27 16:09 id_rsa.pub
8. -rw-r--r-- 1 useb useb 1183 Aug 11 13:57 known_hosts