Git - 连接 Github 远程仓库

762 阅读2分钟

这是我参与8月更文挑战的第一天,本教程记录了本地Git与远程Github仓库连接的方法。设置成功后可以从远程仓库获取代码、将本地代码推送到远端。

准备工作

  • 申请Github账号
  • 基础Git语法知识
  • 本地安装好Git bash运行环境

建立远程仓库

登录Github账号后点击右上角加号建立自己的仓库,名称自拟。

此处以test为例。

配置 SSH 秘钥

创建SSH密钥

在Git bash中执行命令:

ssh-keygen -t rsa -C "abc@163.com"   #此处填自己注册GitHub的邮箱

没有特殊需求的话可以不设置密码,两次回车继续。

~/vvd_git$ ssh-keygen -t rsa -C "zywvvd@mail.ustc.edu.cn"
Generating public/private rsa key pair.
Enter file in which to save the key (/home/zywvvd/.ssh/id_rsa): 
Created directory '/home/zywvvd/.ssh'.
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /home/zywvvd/.ssh/id_rsa.
Your public key has been saved in /home/zywvvd/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:klt1J9JxcGBj7xgB5dC1cXsQmK9ioOhInLRgqKppO8k zywvvd@mail.ustc.edu.cn
The key's randomart image is:
+---[RSA 2048]----+
|      o+p+=o+.   |
|       B.Bo+ o   |
|      = *.+ . .  |
|.    o = *.  .   |
|oo  . . u..      |
|* +   . .        |
|+*.. . .         |
|*E  .  .   .     |
|Ooo              |
+----[SHA256]-----+

得到类似上述输出即为创建成功。得到的文件放在~/.ssh文件夹中。

设置Github

  • 登陆github
  • 在settings中设置 'SSH and GPG keys'
  • 添加new SSH key—— 设置名字并将.ssh 文件夹中isa.pub公钥文件的内容复制进去

测试SSH秘钥

执行命令:

ssh -T git@github.com

输出结果:

Warning: Permanently added the RSA host key for IP address '52.74.223.139' to the list of known hosts.
Hi zywvvd! You've successfully authenticated, but GitHub does not provide shell access.

出现欢迎字段说明SSH密钥配置成功。

测试

同步本地库到远程库上

在已有的本地仓库中使用remote命令链接仓库:

git remote add origin https://github.com/zywvvd/test.git

编辑本地库内容,推送到远程端:

echo "#example" >> README.md
git add README.md
git commit -m "README.md created"
git push -u origin master

此时可以在github端看到更新上传的说明文件。

克隆仓库

执行如下命令以创建一个本地仓库的克隆版本:

git clone /path/to/repository

如果是远端服务器上的仓库,你的命令会是这个样子:

git clone username@host:/path/to/repository