十分钟git-服务器搭建ssh登录

QQ820688215git

微信公众号:shell

 

1首先,建立一个操做系统用户 git,并为其创建一个 .ssh 目录。vim

$ sudo adduser git
$ su git
$ cd
$ mkdir .ssh && chmod 700 .ssh
$ touch .ssh/authorized_keys && chmod 600 .ssh/authorized_keys

2须要为系统用户 gitauthorized_keys 文件添加一些开发者 SSH 公钥。 假设咱们已经得到了若干受信任的公钥,并将它们保存在临时文件中。 与前文相似,这些公钥看起来是这样的:gitauthorized_keys
$ cat /tmp/id_rsa.john.pub
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCB007n/ww+ouN4gSLKssMxXnBOvf9LGt4L
ojG6rs6hPB09j9R/T17/x4lhJA0F3FR1rP6kYBRsWj2aThGw6HXLm9/5zytK6Ztg3RPKK+4k
Yjh6541NYsnEAZuXz0jTTyAUfrtU3Z5E003C4oxOj6H0rfIF1kKI9MAQLMdpGW1GYEIgS9Ez
Sdfd8AcCIicTDWbqLAcU4UpkaX8KyGlLwsNuuGztobF8m72ALC/nLF6JLtPofwFBlgc+myiv
O7TCUSBdLQlgMVOFq1I2uPWQOkOWQAHukEOmfjy2jctxSDBQ220ymjaNsHT4kgtZg2AYYgPq
dAv8JggJICUvax2T9va5 gsg-keypair


3 将这些公钥加入系统用户 git.ssh 目录下 authorized_keys 文件的末尾:bash

$ cat /tmp/id_rsa.john.pub >> ~/.ssh/authorized_keys
$ cat /tmp/id_rsa.josie.pub >> ~/.ssh/authorized_keys
$ cat /tmp/id_rsa.jessica.pub >> ~/.ssh/authorized_keys

4

如今咱们来为开发者新建一个空仓库。能够借助带 --bare 选项的 git init 命令来作到这一点,该命令在初始化仓库时不会建立工做目录:服务器

$ cd /opt/git
$ mkdir project.git
$ cd project.git
$ git init --bare
Initialized empty Git repository in /opt/git/project.git/
上命令Git建立一个空仓库,服务器上的Git仓库一般都以.git结尾。而后,把仓库所属用户改成git:
$ chown -R git:git project.git
 
其余开发者能够克隆此仓库,并推回各自的改动,步骤很简单:



$ git clone git@gitserver:/opt/git/project.git $ cd project $ vim README $ git commit -am 'fix for the README file' $ git push origin master

须要注意的是,目前全部(得到受权的)开发者用户都能以系统用户 git 的身份登陆服务器从而得到一个普通 shell。 若是你想对此加以限制,则须要修改 passwd 文件中(git 用户所对应)的 shell 值。微信

借助一个名为 git-shell 的受限 shell 工具,你能够方便地将用户 git 的活动限制在与 Git 相关的范围内。该工具随 Git 软件包一同提供。 若是将 git-shell 设置为用户 git 的登陆 shell(login shell),那么用户 git 便不能得到此服务器的普通 shell 访问权限。 若要使用 git-shell,须要用它替换掉 bash 或 csh,使其成为系统用户的登陆 shell。 为进行上述操做,首先你必须确保 git-shell 已存在于 /etc/shells 文件中:ssh

$ cat /etc/shells   # see if `git-shell` is already in there.  If not...
$ which git-shell   # make sure git-shell is installed on your system.
$ vim /etc/shells  # and add the path to git-shell from last command

如今你可使用 chsh <username> 命令修改任一系统用户的 shell:工具

$ chsh git  # and enter the path to git-shell, usually: /usr/bin/git-shell   将 /usr/bin/git-shell复制回车
 
 
   

这样,用户 git 就只能利用 SSH 链接对 Git 仓库进行推送和拉取操做,而不能登陆机器并取得普通 shell。 若是试图登陆,你会发现尝试被拒绝,像这样:spa

$ ssh git@gitserver
fatal: Interactive git shell is not enabled.
hint: ~/git-shell-commands should exist and have read and execute access.
Connection to gitserver closed.
相关文章
相关标签/搜索