0%

在 Linux 下搭建 Git 服务器

环境:
服务器 CentOS 7.2 + git(version 1.8.3.1)
客户端 随意

① 安装 Git

Linux 做为服务器端系统,Windows 作为客户端系统,分别安装 Git

服务器端:

#yum install -y git

安装完后,查看 Git 版本

[root@localhost ~]# git --version
git version 1.8.3.1

客户端:

自行下载并安装,安装完之后,查看 Git 版本

$ git --version
git version 2.8.4.windows.1

② 服务器端创建 git 用户,用来管理 Git 服务,并为 git 用户设置密码

[root@localhost home]# id git
id: git:无此用户
[root@localhost home]# useradd git
[root@localhost home]# passwd git

③ 服务器端创建 Git 仓库

设置 /home/git/test.git 为 Git 仓库

然后把 Git 仓库的 owner 修改为 git

[root@localhost git]# mkdir -p test.git
[root@localhost git]# git init --bare test.git
Initialized empty Git repository in /home/git/test.git/
[root@localhost git]# chown -R git:git test.git/

④ 服务器端 Git 打开 RSA 认证

进入 /etc/ssh 目录,编辑 sshd_config,打开以下三个配置的注释:

RSAAuthentication yes
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys

保存并重启 sshd 服务:

[root@localhost ssh]# server sshd restart

由 AuthorizedKeysFile 得知公钥的存放路径是 .ssh/authorized_keys,实际上是 $Home/.ssh/authorized_keys,由于管理 Git 服务的用户是 git,所以实际存放公钥的路径是 /home/git/.ssh/authorized_keys

在 /home/git/ 下创建目录 .ssh

[root@localhost git]# pwd
/home/git
[root@localhost git]# mkdir .ssh
[root@localhost git]# ls -a 
. .. .bash_logout .bash_profile .bashrc .gnome2 .mozilla .ssh

然后把 .ssh 文件夹的 owner 修改为 git

[root@localhost git]# chown -R git:git .ssh
[root@localhost git]# ll -a
总用量 32
drwx------. 5 git  git  4096 8月  28 20:04 .
drwxr-xr-x. 8 root root 4096 8月  28 19:32 ..
-rw-r--r--. 1 git  git    18 10月 16 2014 .bash_logout
-rw-r--r--. 1 git  git   176 10月 16 2014 .bash_profile
-rw-r--r--. 1 git  git   124 10月 16 2014 .bashrc
drwxr-xr-x. 2 git  git  4096 11月 12 2010 .gnome2
drwxr-xr-x. 4 git  git  4096 5月   8 12:22 .mozilla
drwxr-xr-x. 2 git  git  4096 8月  28 20:08 .ssh

⑤ 将客户端公钥导入服务器端 /home/git/.ssh/authorized_keys 文件

[root@localhost git]# cat 公钥 >> .ssh/authorized_keys

也可以使用Vim编辑

⑥ 禁止 git 用户 ssh 登录服务器

之前在服务器端创建的 git 用户不允许 ssh 登录服务器

编辑 /etc/passwd

找到:

git:x:502:504::/home/git:/bin/bash

修改为

git:x:502:504::/home/git:/bin/git-shell

此时 git 用户可以正常通过 ssh 使用 git,但无法通过 ssh 登录系统。

完成

通过以上操作,就实现了使用git自建服务器存放单用户仓库的全部流程;其中,开启RSA不是必需的,使用秘钥一样可以的.

克隆示例

git clone git@{ip/域名:端口}:/home/git/test.git
或使用相对路径
git clone git@{ip/域名:端口}:test.git
  • 本文作者: 6x
  • 本文链接: https://6xyun.cn/article/40
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-ND 许可协议。转载请注明出处!