1. 程式人生 > >Linux上實現ssh免密碼登陸遠程服務器

Linux上實現ssh免密碼登陸遠程服務器

Linux上實現ssh免密碼登陸遠程服務

平常使用ssh登陸遠程服務器時,都需要使用輸入密碼,希望可以實現通過密鑰登陸而免除輸入密碼,從而可以為以後實現批量自動部署主機做好準備。

環境如下:
IP地址 操作系統
服務器端 10.0.0.10 CentOS 6.5 x86
客戶端 10.0.0.61 CentOS 6.5 x86

1.客戶端生成密鑰對

[root@rsync10 ~]# ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Created directory ‘/root/.ssh‘.

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:
99:af:26:b0:23:e2:04:9f:48:02:77:8a:d5:6d:b3:c7 root@rsync10
The key‘s randomart image is:
+--[ RSA 2048]----+
| |
| . . |
|. o o + |
|.+ o . + o |
|+.. . E |
|+o .. . . |
|..o o . |
|o . o . .. |
|.o . . o. |
+-----------------+

查看生成的密鑰對
[root@rsync10 ~]# ls .ssh/
id_rsa id_rsa.pub
id_rsa為私鑰,這個一般需要保密;id_rsa.pub為公鑰,這個可以公開。

2.上傳公鑰到服務器端

使用scp命令操作:

[root@rsync10 ~]# scp .ssh/id_rsa.pub [email protected]:/root/
The authenticity of host ‘10.0.0.61 (10.0.0.61)‘ can‘t be established.
RSA key fingerprint is 83:c2:2d:85:79:f7:20:36:34:1d:53:1c:7a:b0:d9:bc.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added ‘10.0.0.61‘ (RSA) to the list of known hosts.
[email protected]‘s password:
id_rsa.pub 100% 394 0.4KB/s 00:00

3.服務器端操作
把從客戶端傳來的公鑰添加到.ssh/authorized_keys中:

[root@mb01 ~]# mkdir .ssh
[root@mb01 ~]# cat id_rsa.pub >> .ssh/authorized_keys
[root@mb01 ~]# chmod 600 .ssh/authorized_keys

4.修改ssh配置文件/etc/ssh/sshd_config,找到下面一行:

PubkeyAuthentication no
修改為:

PubkeyAuthentication yes

5.測試

[root@rsync10 ~]# ssh [email protected]
Last login: Wed May 2 13:39:22 2018 from 10.0.0.10
[root@mb01 ~]#

6.註意事項

  1. 在服務器端需要把selinux關閉,否則最後無法使用密鑰進行遠程登陸;
  2. 客戶端使用scp命令時,在服務器端也需要安裝ssh客戶端,否則無法把公鑰上傳到服務器端,另外也可以使用ssh-copy-id [email protected]來代替scp操作(這樣在服務器端也不需要執行創建.ssh目錄等這些操作,即相當於該命令可以一步幫我們完成密鑰的上傳與配置工作);

Linux上實現ssh免密碼登陸遠程服務器