使用sshkey的方式访问gitlab

时间:2023-03-09 03:06:57
使用sshkey的方式访问gitlab

在使用jenkins创建jobs的时候配置git为ssh访问的方式报错

记录错误信息

Failed to connect to repository : Command "/usr/bin/git ls-remote -h git@192.168.1.5:isuyang/isuyang-web-www.git HEAD" returned status code 128:
stdout:
stderr: Permission denied, please try again.
Permission denied, please try again.
Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).
fatal: The remote end hung up unexpectedly

因为使用gitlab的ssh访问方式可以不用每次都输入密码。

折腾我好久啊,苍天啊!终于搞定了!再次记录一下!

步骤

声明

我的gitlab和jenkins都是安装在同一个服务器上的,如果你的不在同一台服务器,可以参考

两外一篇笔记:【SSH免密码登陆的方式】去设置:

http://cddaeec9.wiz03.com/share/s/3dSKX92EukLW2hw5300gKpTx1jKMc30ywQms2wZFRD0ujDzF

配置服务器ssh免密码登录

登录服务器切换到git账户

[root@localhost ~]# su - git
[git@localhost ~]$

生成秘钥和公钥之前我先删除掉.ssh目录下的所有文件(非必须)

[git@localhost ~]$ rm -rf /home/git/.ssh/*

创建公钥和私钥

执行命令:ssh-keygen -t rsa -C "529572571@qq.com"

一路Enter;

[git@localhost .ssh]$ ssh-keygen -t rsa -C "529572571@qq.com"
Generating public/private rsa key pair.
Enter file in which to save the key (/home/git/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/git/.ssh/id_rsa.
Your public key has been saved in /home/git/.ssh/id_rsa.pub.
The key fingerprint is:
37:28:62:b8:e0:57:9b:f7:1a:46:32:d2:e8:54:42:ef 529572571@qq.com
The key's randomart image is:
+--[ RSA 2048]----+
| . |
| . . |
| . o |
| .* . |
|. .+oE..S o |
|..ooo.*. . . |
| ..o o + |
| . o o |
| ... |
+-----------------+

查看生成的秘钥文件

[git@localhost .ssh]$ ll
total 8
-rw-------. 1 git git 1675 Sep 23 16:29 id_rsa
-rw-r--r--. 1 git git 398 Sep 23 16:29 id_rsa.pub

带后缀.pub的是公钥文件

不带后缀的是私钥文件

将公钥文件写入到authorized_keys文件中

执行命令:cat id_rsa.pub >> authorized_keys

[git@localhost .ssh]$ cat id_rsa.pub >> authorized_keys

修改authorized_keys的文件权限

执行命令:chmod 600 ~/.ssh/authorized_keys

[git@localhost .ssh]$ chmod 600 ~/.ssh/authorized_keys

修改SSH配置文件,并重启ssh服务

这个配置文件在/etc/ssh/sshd_config中

需要root用户去修改,所以要切换到root上。

把图中圈住的三个地方放开

使用sshkey的方式访问gitlab

执行命令:service sshd restart

使用sshkey的方式访问gitlab

测试一下

如果执行命令:

git ls-remote -h 项目的地址

能够不让输入密码就成功了!

[git@localhost .ssh]$ /usr/bin/git ls-remote -h git@192.168.1.5:isuyang/isuyang-web-sso.git
5033dfcb30a079d9cf9088778ac763817101e27b refs/heads/master

配置gitlab

添加gitlab ssh keys

使用sshkey的方式访问gitlab

注意key为下图中文件的内容:

使用sshkey的方式访问gitlab

配置jenkins

进入job里面找到【配置】

使用sshkey的方式访问gitlab

找到源码管理:

在Respository URL这一栏输入下图中的地址:

使用sshkey的方式访问gitlab

配置 Credentials

未配置之前:

使用sshkey的方式访问gitlab

Add--->Jenkins

使用sshkey的方式访问gitlab

使用sshkey的方式访问gitlab

再次强调private key的内容是下图中文件的全部内容:

使用sshkey的方式访问gitlab

添加之后,选中刚刚添加的信息,就不报错了!

使用sshkey的方式访问gitlab

注意:

网上说需要重启jenkins,我没有重启,你可以先尝试一下如果还报错可以重启试试。