CentOS与GitLab配置SSH的完整流程
确保CentOS系统已安装GitLab且服务正常运行(可通过sudo gitlab-ctl status
检查),并具备root或sudo权限。
SSH密钥对是实现无密码认证的核心,包含私钥(id_rsa
,本地保存)和公钥(id_rsa.pub
,上传至GitLab)。
Ctrl+Alt+T
进入终端。ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
-t rsa
:指定密钥类型为RSA(兼容性好)。-b 4096
:指定密钥长度为4096位(当前安全标准)。-C "your_email@example.com"
:添加注释(通常用注册GitLab的邮箱标识密钥)。~/.ssh/id_rsa
,私钥;~/.ssh/id_rsa.pub
,公钥)。若需自定义路径,可直接输入(如/home/user/.ssh/my_git_key
)。为确保SSH服务安全,需正确设置.ssh
目录及密钥文件的权限:
chmod 700 ~/.ssh # 限制仅所有者可读、写、执行.ssh目录 chmod 600 ~/.ssh/id_rsa # 私钥必须为仅所有者可读写 chmod 644 ~/.ssh/id_rsa.pub # 公钥可设置为所有者可读写、其他用户可读
公钥需上传至GitLab账户,用于验证身份并实现无密码访问。
cat ~/.ssh/id_rsa.pub | xclip -sel clip
若未安装xclip
,可通过sudo yum install xclip
安装;Windows系统可直接用记事本打开~/.ssh/id_rsa.pub
文件复制内容。通过测试连接确认SSH配置是否正确,能否实现无密码访问GitLab。
ssh -T git@gitlab.example.com
将gitlab.example.com
替换为你的GitLab服务器域名或IP地址(如gitlab.yourcompany.com
或192.168.1.100
)。Welcome to GitLab, @your_username!
)。.ssh
目录及密钥文件权限是否正确(参考步骤三)。/etc/gitlab/gitlab.rb
中的gitlab_rails['gitlab_shell_ssh_port']
是否与ssh
命令使用的端口一致(默认22,若修改需同步调整)。配置完成后,可通过SSH协议克隆GitLab仓库,无需每次输入用户名和密码。
git@gitlab.example.com:username/projectname.git
)。git clone git@gitlab.example.com:username/projectname.git
执行后,Git会自动使用本地SSH密钥进行认证,无需输入密码。sudo firewall-cmd --permanent --add-service=ssh sudo firewall-cmd --reload
~/.ssh/config
文件是否配置正确(如指定自定义密钥路径)。git
用户对~/.ssh/authorized_keys
文件有读取权限(通常为600
)。通过以上步骤,即可在CentOS系统上完成GitLab的SSH配置,实现安全、便捷的代码托管与协作。