【熟能生巧】配置多個SSH免密碼登入實戰
需求
本地有一臺機器使用Linux系統,需要SSH(免密碼登入)到雲端的兩臺Server上。
按照網上的教程試了一下,發現配置第一臺可以,配置第二臺的時候就有些問題了。於是花了些時間研究了下,下面是詳細的過程。
至於SSH的原理,可以參考搜尋這裡:[Public-key cryptography] https://en.wikipedia.org/wiki/Public-key_cryptography
流程
大致流程如下,特別要注意括號裡面的內容,是關鍵!
- 首先,生成一對金鑰
Public Key
-Private Key
。 - 然後,把
Private Key
在本地自己藏好。(且告訴系統去哪找這個Key) - 然後,把
Public Key
上傳到目標伺服器上。(且告訴系統這個Key是可信的,可以用來登入)
前置條件
生成的key都是放在.ssh
下面的,.ssh
的路徑一般是/root/.ssh
或者~/.ssh
。
生成
執行命令ssh-keygen
,下面是出來的結果:
Generating public/private rsa key pair. Enter file in which to save the key (/root/.ssh/id_rsa): /root/.ssh/id_rsa_keya Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in /root/.ssh/id_rsa_keya. Your public key has been saved in /root/.ssh/id_rsa_keya.pub.
特別要注意的是,有一步,讓你選擇檔案的名稱和位置,這裡最好自己輸入一個檔名,從而如果有多個key的時候可以區分開來。
Enter file in which to save the key (/root/.ssh/id_rsa): /root/.ssh/id_rsa_keya
-> 比如這裡我們就命名為id_rsa_keya
。
總結,這一步生成了兩個key,且放在了本地的/root/.ssh
目錄下
id_rsa_keya
- Private Keyid_rsa_keya.pub
- Public Key
配置 Public Key
將Public Key上傳並新增到目標伺服器上
執行命令ssh-copy-id -i ~/.ssh/id_rsa_keya.pub user@host
(user和host自己根據情況改掉)
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "id_rsa_keya.pub"
The authenticity of host '139.999.999.999 (139.999.999.999)' can't be established.
ECDSA key fingerprint is SHA256:G6ejPxxxxxxxxxxxRKexxxxxxxxxJcVaFPKx0.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
這裡它會問是不是要把這個host加入到信任列表中,點yes。這一步操作,會更改~/.ssh/known_hosts
檔案的內容。下一次,如果從同一個IP登入,就不會再詢問了。
這次上傳要輸入伺服器的密碼,完成了之後,會顯示如下:
/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.
總結,這一步做了兩個操作:
- 將
id_rsa_keya.pub
放到了server上的~/.ssh/
目錄下。 - 將
id_rsa_keya.pub
的值append到了~/.ssh/authorized_keys
這個檔案裡。這一步授權很關鍵,否則你用自己的私鑰連是沒用的。
配置 Private Key
這裡,我們需要告訴系統,當我登入伺服器A時,你去拿id_rsa_keya
這個key做校驗。(不設定的話,預設會拿id_rsa
)
vim ~/.ssh/config
加入如下內容:
Host aliyun
HostName aliyun
User user
Port 22
IdentityFile ~/.ssh/id_rsa_keya
vim /etc/hosts
加入如下內容:
139.999.999.999 aliyun aliyun
當然,這兩步也可以合為一步。這裡賣個關子,各位同學可以自行研究下。
連線
最後,我們可以直接使用如下命令進行連線
ssh aliyun
->
Welcome to Alibaba Cloud Elastic Compute Service !
完成!(第二,第三臺,甚至更多server的配置也是一樣的,這裡就不重複了)