Sonar系列:Gitlab集成Sonarqube实现自动检测代码并发送报告给提交者(五)

 

1、GitLab-Runner安装

(1)在Admin面板 -- >Runners,查看GitLab-Runner安装方式

 

 (2)下载安装

# Download the binary for your system
sudo curl -L --output /usr/local/bin/gitlab-runner https://gitlab-runner-downloads.s3.amazonaws.com/latest/binaries/gitlab-runner-linux-amd64

# Give it permissions to execute
sudo chmod +x /usr/local/bin/gitlab-runner

# Create a GitLab CI user
sudo useradd --comment 'GitLab Runner' --create-home gitlab-runner --shell /bin/bash

# Install and run as service
sudo gitlab-runner install --user=gitlab-runner --working-directory=/home/gitlab-runner
sudo gitlab-runner start

(3)命令注册

sudo gitlab-runner register --url http://192.168.44.136/ --registration-token hiSDonwf--4gtjqvcbMb

 

 (4)返回gitlab页面,可以看到刚注册的runner。

 

 

 

2、在项目根目录创建.gitlab-ci.yml文件

 

 

 配置 .gitlab-ci.yml 文件内容:

 

stages:
  - sonarqube_scan
  - sendmail

sonarqube_scan_job:
  stage: sonarqube_scan
  script:
    - mvn clean package
    - sonar-scanner -Dsonar.projectName=$CI_PROJECT_NAME -Dsonar.projectKey=$CI_PROJECT_NAME  -Dsonar.language=java -Dsonar.host.url=http://192.168.44.137:9000 -Dsonar.login=admin -Dsonar.password=abc123!  -Dsonar.sources=src  -Dsonar.java.binaries=target/classes  -Dsonar.java.test.binaries=target/test-classes  -Dsonar.ws.timeout=30 -Dsonar.sources=src -Dsonar.sourceEncoding=UTF-8  -Dsonar.java.binaries=target/classes  -Dsonar.java.test.binaries=target/test-classes  -Dsonar.java.surefire.report=target/surefire-reports
  tags:
    - demo
  when: always

sendmail_job:
  stage: sendmail
  script:
    - echo $GITLAB_USER_EMAIL
    - echo $CI_PROJECT_NAME
    - echo $CI_COMMIT_REF_NAME
    - python3 /opt/sonarqube_api.py $CI_PROJECT_NAME $CI_COMMIT_REF_NAME $GITLAB_USER_EMAIL
    
  tags:
    - demo

 

 

 

sonarqube_api.py代码如下:
#!/usr/bin/python
# -*- coding: UTF-8 -*-

import requests,json,sys,time
import smtplib
from email.mime.text import MIMEText
from email.header import Header

from_addr='543395404@qq.com'   #邮件发送账号
qqCode='lejuimybvccobehh'   #授权码
smtp_server='smtp.qq.com'
smtp_port=465

def getSonarinfo(component):
    sonar_url="http://192.168.44.137:9000/api/measures/component?component={0}&metricKeys=bugs,vulnerabilities,code_smells,ncloc".format(component,)
    print(sonar_url)
    sonar_token ="d5519a4e9018084b98ba39d8f9cd82bee0142505"
    session = requests.Session()
    session.auth = sonar_token,''
    call = getattr(session, 'get')
    res = call(sonar_url)
    binary = res.content
    result = json.loads(binary)
    result_dict = {}
    for info_dict in result["component"]["measures"]:
        result_dict[info_dict["metric"]] = info_dict["value"]
        #print(result_dict)
    return result_dict

def sendmail(to_addrs,mail_msg):
    stmp=smtplib.SMTP_SSL(smtp_server,smtp_port)
    stmp.login(from_addr,qqCode)
    message = MIMEText(mail_msg, 'html', 'utf-8')   
    message['From'] = Header("管理员", 'utf-8')  
    message['To'] = Header("Me", 'utf-8')   
    subject = 'Gitlab代码安全检测结果'
    message['Subject'] = Header(subject, 'utf-8')  

    try:
        stmp.sendmail(from_addr, to_addrs, message.as_string())
    except Exception as e:
        print ('邮件发送失败--' + str(e))
    print ('邮件发送成功')

if __name__ == '__main__':
    project = sys.argv[1]
    branch = sys.argv[2]
    user_email = sys.argv[3]
    time.sleep(10)
    sonarqube_data = getSonarinfo(component=project,)
    project_url = "http://192.168.44.137:9000/dashboard?id={0}".format(project,)
    print(sonarqube_data)

    html_text = """
<!DOCTYPE html>
    <html lang="en">
        <head>
            <title></title>
                <meta charset="utf-8">
        </head>
    <body>
        <div class="page" style="margin-left: 30px">
            <h3>{user_email}, 你好!</h3>
            <h3> 本次提交代码检查结果如下:</h3>
            <h3> 项目名称:{project} </h3>
            <h3> 分支:{branch} </h3>
            <h3>一、总体情况</h3>
                <ul>
                    <li style="font-weight:bold;">
                        本次扫描代码行数: &nbsp; <span style="color:blue">{lines} </span>,
                        bugs: &nbsp;<span style="color:red">{bugs}</span>,
                        Vulnerabilities: &nbsp;<span style="color:red">{vulnerabilities}</span>,
                        Code Smells: &nbsp; <span style="color:red">{code_smells}</span>
                    </li>
                    <li style="font-weight:bold;margin-top: 10px;">
                        URL地址:&nbsp;
                        <a style="font-weight:bold;"
                           href={project_url}>{project_url}
                        </a>
                    </li>
                </ul>
             
</div>
</body>
</html>
""".format(user_email=user_email,project=project,branch=branch,lines=sonarqube_data["ncloc"],bugs=sonarqube_data["bugs"],vulnerabilities=sonarqube_data["vulnerabilities"],code_smells=sonarqube_data["code_smells"],project_url=project_url)
            
    #print(html_text)
    sendmail(to_addrs=user_email,mail_msg=html_text)

 

 

 3、实现效果

(1)模拟用户提交代码,新建测试文件填写测试字符,然后commit提交。

(2)在GitLab,CI/CD-->Pipelines,可以查看运行状态,点击进入可查看详情。

 

 

(3)完成后,用户邮箱收到代码检测报告。

 

 (4)在sonar可以查看到对应的项目检测情况。

 

参考链接:

Gitlab集成Sonarqube自动检测代码并发送报告给提交者

https://www.cnblogs.com/Sunzz/p/13731675.html

https://blog.csdn.net/a49963775222/article/details/110120319

posted @ 2021-09-30 16:33  Bypass  阅读(481)  评论(0编辑  收藏  举报