目標很單純:讓 192.168.1.110(個人機)不必輸入密碼就能 ssh 登入 192.168.1.112(伺服器)。流程本身不難,但收尾時常會踩到 ssh-agent 的坑。
miao@u32-192-168-1-110:~/.ssh$ ssh-keygen -t rsa Generating public/private rsa key pair. Enter passphrase (empty for no passphrase): (直接 Enter) Enter same passphrase again: (直接 Enter) Your identification has been saved in /home/miao/.ssh/id_rsa. Your public key has been saved in /home/miao/.ssh/id_rsa.pub.
miao@u32-192-168-1-110:~/.ssh$ scp id_rsa.pub miao@192.168.1.112:/home/miao/.ssh/192.168.1.110 miao@192.168.1.112's password: id_rsa.pub 100% 404 0.4KB/s 00:00
miao@debian-192-168-1-112:~/.ssh$ cat 192.168.1.110 >> authorized_keys
Step 2 與 3 可以用一行指令合併完成:
miao@Ubuntu-192-168-1-110:~/.ssh$ ssh-copy-id miao@192.168.1.112 Password: Now try logging into the machine, with "ssh 'miao@192.168.1.112'", and check in: .ssh/authorized_keys to make sure we haven't added extra keys that you weren't expecting.
若此時執行 ssh 卻出現:
Agent admitted failure to sign using the key
先用 ps -Af 搭配 grep agent 確認 ssh-agent 是否在跑:
miao@u32-192-168-1-110:~/.ssh$ ps -Af | grep agent
若沒有執行,就手動啟動並把私鑰加入:
miao@u32-192-168-1-110:~/.ssh$ ssh-agent miao@u32-192-168-1-110:~/.ssh$ ssh-add ~/.ssh/id_rsa
這類錯誤通常源自 agent 中載入了不匹配或權限有問題的金鑰。若 ssh-add 仍失敗,檢查 ~/.ssh 與私鑰權限(私鑰應為 600、目錄 700),並確認 authorized_keys 的內容沒有混入重複或舊的金鑰。權限過寬是 ssh 最常見的拒絕原因,這一步幾乎都能解決問題。