要在 Linux 上產生 SSH 登入用的金鑰,可以使用 ssh-keygen 這個指令。
在建立金鑰之前,要先建立 ~/.ssh 這個目錄,並設定正確的權限
mkdir -p ~/.ssh
chmod 700 ~/.ssh
$ ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/home/leeyc/.ssh/id_rsa): 按 Enter
Enter passphrase (empty for no passphrase): 可以不輸入密碼
id_rsa.pub:公開金鑰(public key)
id_rsa:私密金鑰(private key)
將產生的 id_rsa.pub 這個公開金鑰複製到 Linux 伺服器上的 ~/.ssh/authorized_keys 檔案中
ssh leeyc@hr.central-security.com.tw 'mkdir -p ~/.ssh;cat >> ~/.ssh/authorized_keys' < ~/.ssh/id_rsa.pub
或者用 ssh-copy-id
ssh-copy-id leeyc@hr.central-security.com.tw
預設會將 ~/.ssh/id_rsa.pub 這個公開金鑰複製到伺服器上,若要指定使用的金鑰,可以使用 -i 參數
ssh-copy-id -i ~/.ssh/id_rsa.pub leeyc@hr.central-security.com.tw
可以在伺服器上的 /etc/ssh/sshd_config 中修改以下的設定,停用密碼認證的登入方式,只允許金鑰認證
PasswordAuthentication no
PubkeyAuthentication yes
ssh 'leeyc@hr.central-security.com.tw'
chmod 700 ~/.ssh