实验环境
序号 | IP | 主机名 | 用户名 |
---|---|---|---|
1 | 192.168.0.112 | bjk | wangxianfeng |
2 | 192.168.0.151 | sbjk | wangxianfeng |
新建用户
新建用户wangxianfeng,创建完成之后分别已用户wangxianfeng登录2台主机。
实验要达到的效果
主机bjk和sbjk的wangxianfeng用户能够相互免密登录或者远程操作。
操作步骤
生成公钥私钥对
在bjk主机上执行:
$ ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/wangxianfeng/.ssh/id_rsa):
Created directory '/home/wangxianfeng/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/wangxianfeng/.ssh/id_rsa.
Your public key has been saved in /home/wangxianfeng/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:DaFi1XrI7NiLfsklyBFvg1i+yI+yNxd42henzramHzo wangxianfeng@bjk
The key's randomart image is:
+---[RSA 3072]----+
| ... |
| o. ... |
| +o*.o. |
| ..+.O .o |
| . + O oS . |
| + B = o |
| * +.O |
|. = EoX. |
|.+ ++X=. |
+----[SHA256]-----+
查看生成的文件:
[wangxianfeng@bjk ~]$ cd .ssh/
[wangxianfeng@bjk .ssh]$ ll
total 8
-rw------- 1 wangxianfeng wangxianfeng 2602 Nov 19 08:24 id_rsa
-rw-r--r-- 1 wangxianfeng wangxianfeng 570 Nov 19 08:24 id_rsa.pub
把bjk的公钥文件内容放入到sbjk的authorized_keys中
登录sbjk主机,把bjk的id_rsa.pub内容放入到sbjk的authorized_keys文件中。
[wangxianfeng@sbjk .ssh]$ pwd
/home/wangxianfeng/.ssh
[wangxianfeng@sbjk .ssh]$ echo 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDQSB03rTN2eP27zpwaYEehllO1S1g/KHPyQWqZ6A7p0Ai+zf/5lJ0cqN2iR9dzHDMR6swwjFt1q5mcaxYy29pbCz8E3eTGc0TLgdggipLamEXUG5lerALyjmlwhKCdgMTHnRjKPU/LI7BBbXmDAk02osG/JxjTsbQAi8/dMkJmoIEuA0Qkzl2fLyFPXnbJFQSkBaIpLwfNZFCZNcqx+YlbtQHtdvG2QYVBHjEiXL0aGlpWY9iYVUSn6k5hNC+xK87KY73N3zsgpUkD6Qdep5DcX0Rje63i5BDC6ux4i+W0u98j52zcLeyYGbKFdqo1GtyfbouXepSbhgWpVXJuuCO0pvMRsx1fQhz3s3uZHKeHc7ys830WNjIBmb/b4f+0WOgMa5XhP3rM5hXVYbbJ4ctGrHFWZ+SIoKH8+zghIDZDaaHmH9VUj7CH0genD+W6gNQ8l8Oy5YL2I6P/7Ya8ELMrHF6YPP0iWpHKretmzKJqgghDMRYHc20bIQDvvWY2bTs= wangxianfeng@bjk' >> authorized_keys
设置authorized_keys文件权限:
chmod 600 authorized_keys
这样就可以从bjk无密码ssh到sbjk主机,测试一下:
[wangxianfeng@bjk .ssh]$ hostname
bjk
[wangxianfeng@bjk .ssh]$ ssh wangxianfeng@192.168.0.151
Welcome to Huawei Cloud Service
Last login: Sat Nov 19 08:36:45 2022 from 192.168.0.112
[wangxianfeng@sbjk ~]$ hostname
sbjk
ssh成功,跳转成功。把sbjk的id_rsa.pub内容放入到bjk的authorized_keys文件中,这样就可以从sbjk无密码登录到bjk主机。
[wangxianfeng@sbjk .ssh]$ hostname
sbjk
[wangxianfeng@sbjk .ssh]$ ssh wangxianfeng@192.168.0.112
wangxianfeng@192.168.0.112: Permission denied (publickey,gssapi-keyex,gssapi-with-mic).
但是,从sbjk ssh登录到bjk主机的时候,出现错误。解决方法是配置root用户编辑/etc/ssh/sshd_config文件以下内容,即RSA认证和公钥认证都要为yes:
RSAAuthentication yes
PubkeyAuthentication yes
配置完成之后,重启sshd服务
[root@bjk ~]# systemctl restart sshd
再次测试从sbjk ssh登录到bjk主机:
[wangxianfeng@sbjk .ssh]$ hostname
sbjk
[wangxianfeng@sbjk .ssh]$ ssh wangxianfeng@192.168.0.112
Welcome to Huawei Cloud Service
Last login: Sat Nov 19 08:58:59 2022 from 192.168.0.151
[wangxianfeng@bjk ~]$ hostname
bjk
成功。
文章评论