[Linux] 產生 SSH key 來免密碼登入 SSH server

[Linux] 產生 SSH key 來免密碼登入 SSH server

在登入 SSH server 時,通常是要打密碼才能登入,

可是對於很常使用的 SSH server 而言,每次 ssh/scp 都得打密碼實在是件苦差事…

學習了一下產生 SSH key 的方法,發現蠻簡單的,

之後就不用再打密碼登入囉~

 

以下步驟是參考 SSH login without password 這篇文章做成的,

假設想從 (主機 A,帳號 build) 自動登入 (主機 B,帳號 test):

基本上就是在主機 A 上產生 SSH public/private keys,

然後把這個主機 A 的 public key 放到主機 B 上的 ~/.ssh/authorized_keys 這檔案裡,

之後從主機 A 登入主機 B 時,就不需要打密碼了~

 

1. 在主機 A 上產生 SSH key

先用帳號 build (或是你想要的帳號) 登入主機 A,用 ssh-keygen 產生 SSH key pair,

加個 -t rsa 確保產生的是 RSA key…不過一般不打好像也是預設這個:

[build@machine-a .ssh]$ ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/build/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/build/.ssh/id_rsa.
Your public key has been saved in /home/build/.ssh/id_rsa.pub.

 

產生出來的 public/private key 會儲存在此帳號的 ~/.ssh 目錄下,

分別是 id_rsa.pub 和 id_rsa:

[build@machine-a .ssh]$ ll
-rw-------. 1 build build 1675 2014-08-31 09:37 id_rsa
-rw-r--r--. 1 build build  409 2014-08-31 09:37 id_rsa.pub
-rw-r--r--. 1 build build 1180 2014-08-31 09:29 known_hosts

 

2. 將剛產生的 id_rsa.pub 內容加到主機 B 的 ~/.ssh/authorized_keys 檔案裡

可以用 vi 把 id_rsa.pub 的內容加進來,或是用 echo append 的方式,

反正就是把主機 A 上的 public key 內容放進去~

放進去之後,應該可以看到類似下面的內容,

可以把主機名稱的部分編輯一下(像是我這邊改成 build@machine-a),方便辨識:

test@machine-b ~/.ssh $ cat authorized_keys
ssh-rsa ***encrypted*** build@machine-a

 

3. 設定 ~/.ssh 目錄和 ~/.ssh/authorized_keys 檔案的權限

這邊要記得把 ~/.ssh 目錄設成 700,authorized_keys 檔案設成 640。

[test@machine-b ~]$ chmod 700 ~/.ssh
[test@machine-b ~]$ ll -d ~/.ssh
drwx------. 2 build build 58 Oct 16 17:39 /home/build/.ssh
[test@machine-b ~]$ cd .ssh
[test@machine-b .ssh]$ chmod 640 authorized_keys
[test@machine-b .ssh]$ ll
total 12
-rw-r-----. 1 build build  403 Oct 16 17:39 authorized_keys
-rw-------. 1 build build 1679 Oct 16 17:39 id_rsa
-rw-r--r--. 1 build build  409 Oct 16 17:39 id_rsa.pub

 

4. 從主機 A 上使用 SSH 登入主機 B

前面的步驟設定好之後,就可以用 ssh / scp 直接從主機 A 登入主機 B 了~

不用每次都再打密碼,方便多囉~~^^


 

2015/11/05 補充:後來才發現有 ssh-copy-id 這個好物可以用,這樣步驟 2 和 3 就可以省略了~

在 Mac 上,可以用 Homebrew 裝好 ssh-copy-id:

brew install ssh-copy-id

 

接著就能直接在 A 機器上,直接執行 ssh-copy-id 將 SSH public key 複製到機器 B 了,

目錄權限也會自動設定好喔:

[build@machine-a .ssh]$ ssh-copy-id test@machine-b
/usr/local/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/local/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
test@machine-b's password:
Number of key(s) added:        1
Now try logging into the machine, with:   "ssh 'test@machine-b'"
and check to make sure that only the key(s) you wanted were added.

 

 

//
//

(本頁面已被瀏覽過 6,647 次)

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料