1
  • root用户的终端提示符#在代码块中会影响显示效果,暂用$代替
  • 使用虚拟机可以在一开始生成快照,然后后面就可以重复进行这个实验

环境参数:

  • 虚拟机 VMware Workstation
  • XShell 6
  • centos7
  • git bash
  • win10

接着开启虚拟机,使用XShell以root用户进行远程登录。

修改镜像文件

如果是在阿里云上安装git服务器则不用修改镜像文件
  1. 先备份原镜像文件,以便出错的时候方便恢复

    root$ cp /etc/yum.repos.d/CentOS-Base.repo{,.bak}
  2. 下载新的CentOS-Base.repo/etc/yum.repos.d/

    root$ wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo
  3. 运行yum makecache 生成缓存

    root$ yum makecache

注:其他版本可以查看http://mirrors.aliyun.com/repo/

安装git

root$ yum install git-core

接下来创建一个git用户组和用户

root$ groupadd git
root$ useradd git -g git

设置git用户密码,然后切换到git用户进行操作

root$ passwd git
root$ su - git

初始化Git仓库

首先我们选定一个目录作为Git仓库,假定是/home/git/gitrepo/git-test.git,在/home/git/目录下输入命令:

git$ cd ~
git$ mkdir gitrepo
git$ cd gitrepo
git$ git init --bare git-test.git
Initialized empty Git repository in /home/git/gitrepo/git-test.git/

克隆仓库

git$ git clone git@10.13.16.47:/home/git/gitrepo/git-test.git
Cloning into 'git-test'...
git@10.13.16.47's password:
warning: You appear to have cloned an empty repository.

到此git服务器已经搭建完毕,而且可以在客户端克隆代码,但是每次都要输入密码,接下来就是解决这个问题。

创建证书登录

在git家目录下建立.ssh 目录以及authorized_keys 文件来管理所有用户的 SSH 公钥

git$ cd ~
git$ mkdir .ssh
git$ touch .ssh/authorized_keys

win10某个文件夹下右键后点击git bash here菜单,然后将公钥文件上传到git用户家目录下(生成公钥的步骤省略了...)

scp ~/.ssh/id_rsa.pub root@10.13.16.47:/home/git

id_rsa.pub文件内容添加到authorized_keys文件末尾

git$ cd ~
git$ cat ./id_rsa.pub >> .ssh/authorized_keys 

然后在git bash的终端进行免密登录测试

ssh -v git@10.13.16.47

很不幸的是,终端提示还是要求用户输入密码!

解决办法:

使用root用户登录,修改一下git用户家目录下.ssh文件夹和.ssh/authorized_keys文件的权限即可:

root$ cd /home/git/
root$ chmod 755 .ssh
root$ chmod 644 .ssh/authorized_keys

再次在git bash终端执行ssh -v git@10.13.16.47命令,免密登录成功!

最后将远程仓库代码克隆到本地且无需输入密码,效果图如下:
免密克隆远程仓库代码


参考链接:

  1. Centos修改镜像为国内的阿里云源
  2. Git 服务器搭建
  3. 在个人服务器上搭建git服务,创建属于自己的私人仓库
  4. 安装 Git

v哥在coding
4 声望0 粉丝

知识应该被分享而不是被淹没