---
title: "同时管理多个ssh私钥【转载】"
author: "jimmee"
date: "2016-03-27T09:13:01Z"
tags: ["Git", "Github", "SSH"]
categories: ["开源软件"]
slug: "ssh"
draft: false
lastmod: "2016-03-27T09:13:01Z"
id: 2286524
url: "https://jimmee.iteye.com/blog/2286524"
---

在设置github的时候，[官方的说明文档](http://help.github.com/set-up-git-redirect "set up git")要求备份当前的id\_rsa，然后生成一份新的私钥用于github的登陆。如果真这样做，那么新的私钥是无法再继续登陆之前的机器的。这种方法有点暴力…  
还好ssh可以让我们通过不同的私钥来登陆不同的域。

首先，在新增私钥的时候，通过指定不同的文件名来生成不同的私钥文件

```
ssh-keygen -t rsa -f ~/.ssh/id_rsa.work -C "Key for Work stuff"
ssh-keygen -t rsa -f ~/.ssh/id_rsa.github -C "Key for GitHub stuff"
```

新增ssh的配置文件，并修改权限

```
touch ~/.ssh/config
chmod 600 ~/.ssh/config
```

修改config文件的内容

```
1
2
3
4
5
6
7
```

```
Host *.workdomain.com
    IdentityFile ~/.ssh/id_rsa.work
    User lee
 
Host github.com
    IdentityFile ~/.ssh/id_rsa.github
    User git
```

这样在登陆的时候，ssh会根据登陆不同的域来读取相应的私钥文件

```
.ssh: lee$ ssh -vT git@github.com
OpenSSH_5.2p1, OpenSSL 0.9.8r 8 Feb 2011
debug1: Reading configuration data /Users/lee/.ssh/config
debug1: Applying options for github.com
debug1: Reading configuration data /etc/ssh_config
debug1: Connecting to github.com [207.97.227.239] port 22.
debug1: Connection established.
debug1: identity file /Users/lee/.ssh/id_rsa.github type 1
debug1: Remote protocol version 2.0, remote software version OpenSSH_5.1p1 Debian-5github2
debug1: match: OpenSSH_5.1p1 Debian-5github2 pat OpenSSH*
```