1. 程式人生 > 實用技巧 >linux系統中ssh部署兩臺伺服器遠端免密登入

linux系統中ssh部署兩臺伺服器遠端免密登入

主機1:PC1,192.168.10.10

主機2:PC2,192.168.10.20

以下實現主要實現PC2遠端免密登入PC1

1、測試PC2和PC1主機的連通性

[root@PC2 ~]# ifconfig | head -n 3  ## 檢視PC2主機IP
eno16777728: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.10.20  netmask 255.255.255.0  broadcast 192.168.10.255
        inet6 fe80::20c:29ff:fe25:bb3e  prefixlen 
64 scopeid 0x20<link> [root@PC2 ~]# ping -c 3 192.168.10.10 ## 測試與 PC1連通性 PING 192.168.10.10 (192.168.10.10) 56(84) bytes of data. 64 bytes from 192.168.10.10: icmp_seq=1 ttl=64 time=0.234 ms 64 bytes from 192.168.10.10: icmp_seq=2 ttl=64 time=0.226 ms 64 bytes from 192.168.10.10: icmp_seq=3 ttl=64 time=0.191
ms --- 192.168.10.10 ping statistics --- 3 packets transmitted, 3 received, 0% packet loss, time 2000ms rtt min/avg/max/mdev = 0.191/0.217/0.234/0.018 ms

2、測試PC2直接遠端登入PC1

[root@PC2 ~]# ssh root@192.168.10.10   ## 此時需要密碼驗證
root@192.168.10.10's password: 

3、在PC2端生成祕鑰和公鑰對

[root@PC2 ~]# ssh-keygen    ## 一路回車即可
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: 72:b5:42:a2:c4:f5:34:54:b8:fd:8c:2b:76:7f:5b:61 root@PC2 The key's randomart image is: +--[ RSA 2048]----+ | ..+o. | | . . o.. | | o . oo. | | . . o.... | | . . S .+ E | | o .. o . .| | . .| | o o .. | | . o ..... | +-----------------+
[root@PC2 ~]# ls -a /root/.ssh/      ## 生成的公鑰和祕鑰在這裡
.  ..  id_rsa  id_rsa.pub  known_hosts

4、在PC2端將公鑰傳輸至PC1

[root@PC2 ~]# ssh-copy-id 192.168.10.10
/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
root@192.168.10.10's password:    ## 此處輸入PC1主機的root密碼

Number of key(s) added: 1

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

5、PC2端測試遠端免密登入

[root@PC2 ~]# ssh root@192.168.10.10   ## 此時無需密碼可直接登入
Last login: Wed Dec  2 16:39:39 2020
[root@PC1 ~]# ifconfig | head -n 3
eno16777728: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.10.10  netmask 255.255.255.0  broadcast 192.168.10.255
        inet6 fe80::20c:29ff:fe66:37f7  prefixlen 64  scopeid 0x20<link>
[root@PC1 ~]# exit  ## 退出
logout
Connection to 192.168.10.10 closed.

以上實驗實現了PC2主機遠端免密登入PC1主機