我们经常发布文档更新,此页面的翻译可能仍在进行中。有关最新信息,请访问英文文档。如果此页面上的翻译有问题,请告诉我们

此版本的 GitHub Enterprise 已停止服务 2021-03-02. 即使针对重大安全问题,也不会发布补丁。 要获得更好的性能、改进的安全性和新功能,请升级到 GitHub Enterprise 的最新版本。 如需升级方面的帮助,请联系 GitHub Enterprise 支持

使用 SSH 密钥密码

您可以保护 SSH 密钥并配置身份验证代理,这样您就不必在每次使用 SSH 密钥时重新输入密码。

本文内容

使用 SSH 密钥时,如果有人获得您计算机的访问权限,他们也可以使用该密钥访问每个系统。 要添加额外的安全层,可以向 SSH 密钥添加密码。 您可以使用 ssh-agent 安全地保存密码,从而不必重新输入。

添加或更改密码

通过输入以下命令,您可以更改现有私钥的密码而无需重新生成密钥对:

$ ssh-keygen -p -f ~/.ssh/id_ed25519
> Enter old passphrase: [Type old passphrase]
> Key has comment 'your_email@example.com'
> Enter new passphrase (empty for no passphrase): [Type new passphrase]
> Enter same passphrase again: [Repeat the new passphrase]
> Your identification has been saved with the new passphrase.

如果您的密钥已有密码,系统将提示您输入该密码,然后才能更改为新密码。

在 Git for Windows 上自动启动 ssh-agent

您可以在打开 bash 或 Git shell 时自动运行 ssh-agent。 复制以下行并将其粘贴到 Git shell 中的 ~/.profile~/.bashrc 文件中:

env=~/.ssh/agent.env

agent_load_env () { test -f "$env" && . "$env" >| /dev/null ; }

agent_start () {
    (umask 077; ssh-agent >| "$env")
    . env=~/.ssh/agent.env

agent_load_env () { test -f "$env" && . "$env" >| /dev/null ; }

agent_start () {
    (umask 077; ssh-agent >| "$env")
    . "$env" >| /dev/null ; }

agent_load_env

# agent_run_state: 0=agent running w/ key; 1=agent w/o key; 2= agent not running
agent_run_state=$(ssh-add -l >| /dev/null 2>&1; echo $?)

if [ ! "$SSH_AUTH_SOCK" ] || [ $agent_run_state = 2 ]; then
    agent_start
    ssh-add
elif [ "$SSH_AUTH_SOCK" ] && [ $agent_run_state = 1 ]; then
    ssh-add
fi

unset env

if [ ! "$SSH_AUTH_SOCK" ] || [ $agent_run_state = 2 ]; then
    agent_start
    ssh-add
elif [ "$SSH_AUTH_SOCK" ] && [ $agent_run_state = 1 ]; then
    ssh-add
fi

unset env

如果您的私钥没有存储在默认位置之一(如 ~/.ssh/id_rsa),您需要告知 SSH 身份验证代理其所在位置。 要将密钥添加到 ssh-agent,请输入 ssh-add ~/path/to/my_key。 更多信息请参阅“生成新的 SSH 密钥并添加到 ssh-agent

提示:如果想要 ssh-agent 在一段时间后忘记您的密钥,可通过运行 ssh-add -t <seconds> 进行配置。

现在,当您初次运行 Git Bash 时,系统将提示您输入密码:

> Initializing new SSH agent...
> succeeded
> Enter passphrase for /c/Users/you/.ssh/id_rsa:
> Identity added: /c/Users/you/.ssh/id_rsa (/c/Users/you/.ssh/id_rsa)
> Welcome to Git (version 1.6.0.2-preview20080923)
>
> Run 'git help git' to display the help index.
> Run 'git help ' to display help for specific commands.

ssh-agent 进程将继续运行,直到您注销、关闭计算机或终止该进程。

在密钥链中保存密码

在 OS X Leopard 上通过 OS X El Capitan,这些默认私钥文件将自动处理:

  • .ssh/id_rsa
  • .ssh/identity

初次使用密钥时,系统将提示您输入密码。 如果选择使用密钥链保存密码,则无需再次输入密码。

否则,您可在将密钥添加到 ssh-agent 时在密钥链中存储密码。 更多信息请参阅“添加 SSH 密钥到 ssh-agent”。

延伸阅读