一台电脑上使用两个GitHub账户

本文详细介绍了如何使用ssh-keygen生成并配置多个SSH密钥,以实现同一台计算机上通过不同的GitHub账号进行Git操作。通过修改~/.ssh/config文件和项目.git/config文件,可以指定特定的SSH密钥用于不同的GitHub账号,从而避免了频繁切换SSH密钥的麻烦。

使用ssh-keygen生成两个ssh key,目录内容如下:

$ ll ~/.ssh/
total 15
-rw-r--r-- 1 Cui 197121  336 九月 15 10:25 config
-rw-r--r-- 1 Cui 197121 1675 七月 19 22:56 id_rsa
-rw-r--r-- 1 Cui 197121  398 七月 19 22:56 id_rsa.pub
-rw-r--r-- 1 Cui 197121 1675 九月 15 00:09 id_rsa_other
-rw-r--r-- 1 Cui 197121  398 九月 15 00:09 id_rsa_other.pub
-rw-r--r-- 1 Cui 197121 1989 九月 12 21:57 known_hosts

ssh的config文件如下:

$ cat ~/.ssh/config
# one

    Host github.com

    HostName github.com

    PreferredAuthentications publickey

    IdentityFile ~/.ssh/id_rsa

    User legend9207

# two

    #远程主机地址别名;git config中远程git服务地址可以配置成这个,以达到相同git服务地址使用不同ssh key的目的。
    Host cuiyindeng.github.com

    HostName github.com

    PreferredAuthentications publickey

    IdentityFile ~/.ssh/id_rsa_other

    User cuiyindeng

两个项目的git config文件如下:

项目1目录/.git/config
...
[remote "origin"]
	url = git@github.com:legend9207/legend9207.github.io.git
	fetch = +refs/heads/*:refs/remotes/origin/*
...

项目2目录/.git/config
...
[remote "origin"]
    #此时的git服务地址用的是ssh config中的别名。
	url = git@cuiyindeng.github.com:cuiyindeng/cuiyindeng.github.io.git
	fetch = +refs/heads/*:refs/remotes/origin/*
...

参考文章:https://blog.youkuaiyun.com/wolfking0608/article/details/78512171

在同一台电脑上设置两个GitHub或GitLab账号并分别拉取远程代码库,你需要按照以下步骤操作: 1. **安装Git**:首先确保电脑已经安装了Git。如果没有,可以从官方网站下载并安装最新版本。 2. **配置SSH密钥对**:对于GitHub,你可以按照官方文档创建一个新的SSH密钥对,分别为两个账户生成,然后添加到各自的GitHub帐户设置中。这一步可以让你通过SSH协议无交互登录。 - 对于Windows用户,通常在`%USERPROFILE%\.ssh`目录下会有两个文件,分别为公钥(id_rsa.pub)和私钥(id_rsa),替换到相应的账户关联。 3. **克隆仓库**:打开终端(如果是Windows用户则需要Git Bash或其他Git客户端提供的命令行环境)并切换到你想存放代码的目录,例如: ```bash cd /path/to/repo_directory ``` 4. **初始化新仓库**(如果不存在): ```bash git init ``` 5. **添加远端仓库**,假设其中一个账户的仓库地址是`https://github.com/user1/repository.git`,另一个是`https://github.com/user2/repository.git`,你可以使用: ```bash git remote add origin1 https://github.com/user1/repository.git git remote add origin2 https://github.com/user2/repository.git ``` 6. **切换分支或克隆**:使用`git checkout`或`git clone`命令时,指定对应的origin,比如: ```bash git checkout -b branch_name origin1/branch_name ``` 7. **拉取代码**:当需要更新代码时,使用`git pull`命令,同样指定相应的origin: ```bash git pull origin1 master git pull origin2 feature_branch ``` 现在,你可以在这两个仓库之间自由切换,拉取各自项目的需求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值