一、問題
如上,A機器經常需遠程操作B機器,傳輸文件到B機器,每次輸入帳號密碼過於繁瑣,下文通過ssh公鑰能解免密碼操作問題。
二、解決
1.方案
SSH認證采用公鑰與私鑰認證方式。
2.步驟
1) A機器生成公鑰/私鑰對
[root@host- 08 ~]# ssh-keygen -t rsa -P ''Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
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:
a7:e3:23:45:e4:a2:22:d0:8d:21:f8:fb:9a:18:b7:f2 root@host-08
The key's randomart image is:
+--[ RSA 2048]----+
|. |
|o . . |
| + + o |
|. + . . o |
|. . . oS . |
|. o . .o |
|...o .o |
|.+ o. .... |
|.oE. ... |
+-----------------+
- 說明
1. -P表示密碼,-P '' 就表示空密碼,也可以不用-P參數,這樣就要三次回車,用-P就一次回車。
該命令將在/root/.ssh目錄下面產生一對密鑰id_rsa和id_rsa.pub。2. 一般采用的ssh的rsa密鑰:
id_rsa 私鑰
id_rsa.pub 公鑰
下述命令產生不同類型的密鑰
ssh-keygen -t dsa
ssh-keygen -t rsa
ssh-keygen -t rsa1
2) B機器建.ssh目錄
[root@host- 100 ~]# mkdir . ssh
- 說明
已有.ssh目錄則不需要建立,沒有則建.ssh目錄
3) 將A機器生成的公鑰拷貝到B機器
[root@host- 08 ~]# scp -P 28888 ~/. ssh/id_rsa.pub root@ 192.168. 1.100:/root/. ssh/authorized_keys
The authenticity of host '[192.168.1.100]:28888 ([192.168.1.100]:28888)' can't be established.
RSA key fingerprint is d4:a5:96:40:80:cb:c6:b9:7d:28:46:43:0c:95:49:84.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '[192.168.1.100]:28888' (RSA) to the list of known hosts.
root@192.168.1.100's password:
id_rsa.pub 100% 396 0.4KB/s 00:00
[root@host-08 ~]#
- 說明
1.B機器ssh端口不是默認端口所以需要加參數 "-P 實際端口 "
2.B機器保存A機器公鑰目錄為$HOME/.ssh,公鑰scp拷貝時重命名為 authorized_keys
4) B機器更改authorized_keys(A機器公鑰)文件權限
[root@host- 100 ~]# chmod 600 /root/. ssh/authorized_keys
----------------------------
至此,免密碼配置已完畢。如想要B機器也免密碼登錄A機器,如上步驟目標機器調換一下即可。
5) 測試
SSH免密碼登錄
[root@host- 08 ~]# ssh -p28888 -l root 192.168. 1.100Last login: Tue Jun 14 15:02:37 2016 from 192.168.1.8
[root@host-203 ~]$
SCP免密碼傳輸文件
[root@host- 08 ~]# scp -P 28888 -r /root/findyou.war root@ 192.168. 1.100:/root/findyou.war 100% 8005KB 7.8MB/s 00:01
[root@host-08 ~]#
如轉載還請保留出處與作者姓名Findyou,謝謝!