搭建免密SSH访问的私有Git服务器

Git服务器可以很轻松的搭建在运行Linux的机器上,可以选择Ubuntu、Debian或者CentOS。同时可以在服务器设置开发人员的SSH公钥来实现免密访问。

本文使用CentOS 7来作为Git服务器。

1. 安装Git

在电脑上打开Git bash,运行ssh root@命令,以root身份ssh登录Git服务器,提示登录密码时输入root用户的密码:

$ ssh [email protected]
...
Last login: ...
[root@localhost ~]#

登陆成功后,运行yum install git命令安装Git:

[root@localhost ~]# yum install git

安装后运行git --version命令验证下:

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

安装成功了。接下来运行adduser git命令为Git服务创建一个新的用户:

[root@localhost ~]# adduser git

2. 禁用Git服务器上git用户的shell权限

出于安全考虑,要禁用服务器上git用户的shell访问权限。继续执行vi命令设置shell权限:

[root@localhost ~]# vi /etc/passwd

vi编辑器打开passwd文件后,按INSERT键进入编辑状态,将git:x:1001:1001::/home/git:/bin/bash,修改成git:x:1001:1001::/home/git:/usr/bin/git-shell。修改后键入:x回车保存并退出vi编辑器,。

3. 创建Git仓库

运行mkdir命令在Git服务器上新建Git仓库目录:

[root@localhost ~]# mkdir -p /gitrepo/theoneprj.git

目录创建成功,再运行git init --bare命令创建一个裸库,亦即没有工作目录的Git仓库:

[root@localhost /]# git init --bare /gitrepo/theoneprj.git
Initialized empty Git repository in /gitrepo/theoneprj.git/

接下来运行chown -R命令,将Git仓库目录的权限授权给git用户:

[root@localhost /]# chown -R git:git /gitrepo/theoneprj.git

到这里Git仓库就创建完成了。运行exit命令退出root shell:

[root@localhost ~]# exit
logout
Connection to 10.0.0.50 closed.

4. Git用户访问授权

Git通过SSH协议在网络上传输数据。接下来要做的是为每个开发人员在自己的开发电脑上生成一对SSH密钥(private key & public key),然后将自己的公钥(public key)上传到Git服务器。以后开发人员使用git命令和服务器交互时就可以免密直接访问了。

4.1. 为开发成员生成SSH密钥对

在Git bash中执行命令ssh-keygen -t RSA -C "",命令运行时会要求指定保存密钥对的文件、以及用于保护私钥的密码。连续回车--均采用默认设置生成密钥对。密钥对文件默认保存在C:\Users<当前Windows登录用户>.ssh文件夹内。

$ ssh-keygen -t RSA -C "[email protected]" -f ~/.ssh/id_rsa -P ''
Generating public/private RSA key pair.
Your identification has been saved in id_rsa.
Your public key has been saved in id_rsa.pub.
The key fingerprint is:
SHA256:CWfkVa7vHUj1mQmSW23QmFbo7gcznfr+TJzPrD9RKw0 [email protected]
The key's randomart image is:
+---[RSA 2048]----+
(此处省略)
+----[SHA256]-----+

4.2. 将开发任意的公钥上传到Git服务器

运行下列命令:

$ ssh [email protected]  'mkdir -p /home/git/.ssh && cat >> /home/git/.ssh/authorized_keys' < ~/.ssh/id_rsa.pub

如果提示需要密码则输入root用户的密码即可。

命令执行完成后,测试一下SSH免密登录是否成功:

$ ssh [email protected]
Last login: ...
fatal: Interactive git shell is not enabled.
hint: ~/git-shell-commands should exist and have read and execute access.
Connection to 10.0.0.50 closed.

从命令的返回信息可以看到可以登录了,说明使用git命令时SSH免密登录设置成功(由于禁用了服务器git用户账号的shell权限,所以连接被自动关闭了,这是正常现象)。

到这里私有的Git服务器就搭建好了,现在开发人员在自己的电脑上可以通过git clone [email protected]/gitrepo/theoneprj.git从服务器克隆Git仓库到本地了。

你可能感兴趣的:(搭建免密SSH访问的私有Git服务器)