Linux 添加 Git 用户,开启 SSH 的 RSA 公钥认证并关闭密码认证登陆

刚新装好的服务器,使用 CentOS 6.8 ,一堆东西需要设置。

首先是添加常用的用户,以 Git 为例:

装机自带了 Git,先 yum 更新一下:

1
yum update -y git

接下来新建一个名为 git 的用户:

1
useradd -d /home/git -m git

这里的 -d 选项指定了此用户的主目录为 /home/git , -m 选项表示如果目录不存在则新建目录。

然后就要开始对 git 用户进行一些安全相关的设置。

因为只需要在常用的电脑上操作远程仓库,所以开启 SSH 的 RSA 公钥认证登陆,并关闭 git 用户的密码登陆功能。

修改 /etc/ssh/sshd_config 文件,这里我使用的是 vim 文本编辑器。

1
2
3
4
HostKey /etc/ssh/ssh_host_rsa_key               # 主机私钥文件位置
RSAAuthentication yes # 开启 RSA 认证
PubkeyAuthentication yes # 开启公钥认证
AuthorizedKeysFile .ssh/authorized_keys # 认证公钥文件位置

找到并修改以上 4 条设置,如果被#号注释掉了,删除前面的#号。

然后再文件末尾添加:

1
2
Match User git, Group git
PasswordAuthentication no

这样就开启了 SSH 的 RSA 公钥认证,并禁用了 git 用户的密码认证登陆功能。

认证公钥文件为用户主目录下的 .ssh/authorized_keys 。

接下来 cd 到 git 用户的主目录,创建 .ssh 目录和 authorized_keys 文件,并设置权限。

1
2
3
4
5
cd /home/git
mkdir .ssh
touch .ssh/authorized_keys
chmod 700 -R .ssh
chown -R git:git .ssh

然后编辑 /home/git/.ssh/authorized_keys 文件,将需要登陆的电脑的 RSA 公钥写入进来,每行一个。
并重启 ssh 服务:

1
/etc/init.d/sshd restart

最后,
因为 git 用户仅用于使用 git 服务器上的管理远程仓库,所以我们应该让 git 用户的终端指向 git-shell。

1
usermod -s /usr/bin/git-shell git

现在就可以轻松的在自己的电脑上使用 git 管理服务器上的远程仓库了~

Linux 添加 Git 用户,开启 SSH 的 RSA 公钥认证并关闭密码认证登陆

https://blog.dennic365.com/2017/10/20/linux-add-git-user/

作者

Dennic

发布于

2017-10-20

更新于

2022-02-24

许可协议

评论