centos 7.6 设置 SSH 通过密钥登录

ssh 控制服务器:192.168.48.102
ssh 被控制服务器:192.168.48.103

产生sshd 私钥和公钥:

[root@localhost ~]# ssh-keygen -t rsa -b 4096
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
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:wxBPRyYTDpQQYvp2u86bL3Fza3cCs5V2TAYeFDM1qa4 [email protected]
The key's randomart image is:
+---[RSA 2048]----+
| o o++.=+Ooo. |
| o . . =oo.. |
|. . o. + |
| . o o o |
| o . S. = |
| . ...o +.= o |
| .o o O . |
| ..o E o . |
| .
+.. . o |
+----[SHA256]-----+

查看密钥文件:
[root@localhost ~]# cd /root/.ssh/
[root@localhost .ssh]# ls
id_rsa id_rsa.pub known_hosts

将公钥文件传输到需要远控的机器上:
[root@localhost .ssh]# ssh-copy-id -i /root/.ssh/id_rsa.pub [email protected]
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
[email protected]'s password:

Number of key(s) added: 1

Now try logging into the machine, with: "ssh '[email protected]'"
and check to make sure that only the key(s) you wanted were added.

在远控的机器上要修改sshd配置文件:
[root@localhost .ssh]# vi /etc/ssh/sshd_config
PubkeyAuthentication yes --打开这行的注释

重启服务:
[root@localhost .ssh]# systemctl restart sshd.service

在控制服务器ssh被控制服务器:
[root@localhost .ssh]# ssh -i /root/.ssh/id_rsa [email protected]
Last login: Mon Jun 24 23:37:11 2019 from 192.168.48.101
[root@localhost ~]# ifconfig
ens33: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 192.168.48.103 netmask 255.255.255.0 broadcast 192.168.48.255
inet6 fe80::6a9b:be28:c9bb:64fd prefixlen 64 scopeid 0x20<link>
ether 00:0c:29:e6:e9:b0 txqueuelen 1000 (Ethernet)
RX packets 16635 bytes 16327536 (15.5 MiB)
RX errors 0 dropped 141 overruns 0 frame 0
TX packets 9187 bytes 5350257 (5.1 MiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536
inet 127.0.0.1 netmask 255.0.0.0
inet6 ::1 prefixlen 128 scopeid 0x10<host>
loop txqueuelen 1000 (Local Loopback)
RX packets 188 bytes 16920 (16.5 KiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 188 bytes 16920 (16.5 KiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

猜你喜欢

转载自blog.51cto.com/1556359/2412839