根据我所在的目录自动添加 ssh 密钥

J86*_*J86 0 ssh arch-linux git github

我有两个 GitHub 帐户。一份供个人使用,另一份供商业使用。每个都设置有自己的 SSH 密钥gh_personalgh_business内部~/.ssh.

我有一个个人项目位于~/code/bejebeje. 每次我去从事该项目时,我都必须记住运行以下命令:

eval `ssh-agent -s`       
Run Code Online (Sandbox Code Playgroud)

其次是:

ssh-add ~/.ssh/gh-personal
Run Code Online (Sandbox Code Playgroud)

只有这样我才能做诸如git pull和 之类的事情git push

你猜对了,我总是忘记这样做。

有没有办法让我的 Linux 系统在我进入目录时自动执行此操作~/code/bejebeje

我在 Arch Linux 上。

小智 5

您可以创建ssh_configAKA~/.ssh/config来匹配不同的地址,如下所示:

Host *
  Protocol                 2
  PreferredAuthentications publickey,password
  VisualHostKey            yes

Host work_gh
  HostName                 github.com
  IdentityFile             ~/.ssh/id_rsa.work
  IdentitiesOnly           yes
  ForwardAgent             no
  LogLevel                 DEBUG

Host personal_gh
  HostName                 github.com
  IdentityFile             ~/.ssh/id_rsa.personal
  IdentitiesOnly           yes
  ForwardAgent             no
  LogLevel                 DEBUG
Run Code Online (Sandbox Code Playgroud)

此配置也不需要 ssh-agent ,也不会尝试使用代理,因为请IdentitiesOnly参阅有关man ssh_config可以设置的选项的更多信息ssh_config

回到 git,您可以使用名称“personal_gh”作为要克隆的地址中的主机名:

git clone git@personal_gh:mypersonalghuser/things.git

You can also change existing git repositories:

git remote show origin
* remote origin
  Fetch URL: git@personal_gh:mypersonalghuser/things.git
  Push  URL: git@personal_gh:mypersonalghuser/things.git
  HEAD branch: master
  Remote branch:
    master tracked
  Local branch configured for 'git pull':
    master merges with remote master
  Local ref configured for 'git push':
    master pushes to master (up to date)
Run Code Online (Sandbox Code Playgroud)

如果您有需要推送到两个帐户的存储库,我建议在 git 中添加多个远程并推送,如下所示:

git push my-dest-account-1 master
git push my-dest-account-2 master
Run Code Online (Sandbox Code Playgroud)

您可以通过以下方式添加遥控器:

git remote add --help
Run Code Online (Sandbox Code Playgroud)

无论如何,如果您在 ssh 客户端配置中进行了配置,则使用的 SSH 密钥将根据 git 地址的主机名部分进行匹配,通常~/.ssh/config