教程

如何指定用某把 SSH 密钥(按主机,及给 Git)

用 -i 强制 SSH 用某把私钥,在 ~/.ssh/config 里用 IdentityFile + IdentitiesOnly 永久按主机生效,给 Git 用主机别名或 GIT_SSH_COMMAND 指定密钥。

CC Chen Chen· 创始人·2026 年 6 月 14 日·阅读 5 分钟

如何指定用某把 SSH 密钥

要强制 SSH 用某一把特定私钥,用 -i 指向它:

ssh -i ~/.ssh/work_key user@host

要永久、按主机生效——并阻止 SSH 先去试你其它密钥——用 ~/.ssh/configIdentityFile + IdentitiesOnly。Git 的话,最干净的是按主机配置或 GIT_SSH_COMMAND。逐个来。

一次性:-i 参数

ssh -i ~/.ssh/work_key user@host

适合快速测试。但单用 -i 只是把那把密钥加进要试的列表——如果你装了好几把,它可能仍先递别的、撞上 too many authentication failures。要递这一把,加 -o IdentitiesOnly=yes:

ssh -i ~/.ssh/work_key -o IdentitiesOnly=yes user@host

永久:~/.ssh/config 按主机

"这台服务器永远用这把密钥"的正确做法——配一次就忘:

Host work
    HostName 203.0.113.7
    User deploy
    IdentityFile ~/.ssh/work_key
    IdentitiesOnly yes

现在 ssh work 正好用那把、不递别的。IdentitiesOnly yes 是关键那行——没它,客户端仍会先把你其它密钥在服务器面前排队。(更多见 SSH 配置文件指南。)

给 Git 指定密钥

两个干净选项。按主机配置——给你的 Git 主机一个带自己密钥的别名:

Host github.com
    HostName github.com
    User git
    IdentityFile ~/.ssh/github_key
    IdentitiesOnly yes

或者,对单条命令,覆盖 Git 用的 SSH 命令:

GIT_SSH_COMMAND="ssh -i ~/.ssh/github_key -o IdentitiesOnly=yes" git clone [email protected]:user/repo.git

多个 Git 账号时配置法更好:给每个一个自己的 Host 别名(如 github-work),用别名 clone。

在手机上

移动客户端不用 ~/.ssh/config——它们按连接固定密钥。在 TermAI 里,每条保存的连接有自己的认证设置,所以"这台服务器用这把特定密钥"就是在那条连接上选中那把密钥;它就只递这一把。IdentitiesOnly 的等价物是自动的,你永远不会撞上密钥太多的错。

手机上配置了单把特定密钥的 SSH 连接
在手机上你按连接选密钥——相当于 IdentityFile + IdentitiesOnly,在表单里配一次。

常见问题

怎么让 SSH 用某把特定密钥?
单条命令用 ssh -i ~/.ssh/key user@host,或在 ~/.ssh/configHost 块里设 IdentityFile 永久按主机生效。加 IdentitiesOnly yes 让它只递那把。

IdentitiesOnly 是干什么的?
它阻止客户端把你 agent 和 ~/.ssh 里的每把密钥也递出去。没它,-i 只是把你的密钥加进列表,可能触发 "too many authentication failures"。

怎么给 Git 指定某把 SSH 密钥?
给主机一个带自己 IdentityFile~/.ssh/config 块,或对单条命令设 GIT_SSH_COMMAND="ssh -i ~/.ssh/key -o IdentitiesOnly=yes"

能给不同 GitHub 账号用不同密钥吗?
能——在 ~/.ssh/config 里给每个账号建一个 Host 别名、各带自己密钥,用别名 clone。

快速事实

  • 一次性:ssh -i ~/.ssh/key -o IdentitiesOnly=yes user@host
  • 永久:~/.ssh/configHostIdentityFile + IdentitiesOnly yes
  • Git:按主机配置,或单条命令 GIT_SSH_COMMAND
  • 为何要 IdentitiesOnly:单用 -i 仍会递别的密钥 → too-many-auth
  • 移动端:按连接选密钥(IdentitiesOnly 自动)
Try TermAI

Free on iOS and Android. 5 AI requests/day on the free tier, plus unlimited SSH/SFTP and built-in Tailscale.

CC
Chen Chen — Founder of TermAI

Writes about mobile DevOps, terminal UX, and the surprising depth of "boring" infrastructure.

Was this useful? ← Back to blog