Python實(shí)現(xiàn)獲取sonarqube數(shù)據(jù)
1.sonarqube是一款代碼分析的工具,通過soanrScanner掃描后的數(shù)據(jù)傳遞給sonarqube進(jìn)行分析
2.sonarqube社區(qū)版沒有對c++類代碼的分析,但是可以找到一個(gè)開源的包,安裝即可,掃描的話可以使用cppcheck來進(jìn)行掃描
- 安裝python對于sonarqube的api包:python-sonarqube-api
- 建立sonarqube連接
from sonarqube import SonarQubeClient
sonar = SonarQubeClient(
sonarqube_url="http://192.168.xx.xx:9000",
username='admin',
password='admin'
)
使用:建議大家先參考sonarqube的python-api
使用示例
# 通過項(xiàng)目名稱獲取id
# 傳遞參數(shù):創(chuàng)建分析配置文件時(shí)候的項(xiàng)目名稱
component = sonar.components.get_project_component_and_ancestors("python_test")
# 獲取任務(wù)
# 參數(shù)1:上一步獲取的component值
# 參數(shù)2:逗號分割的狀態(tài)值
tasks1 = sonar.ce.search_tasks(
componentId="AX5v36mo0Npud3J2od3a",
status="FAILED,CANCELED,PENDING,IN_PROGRESS,SUCCESS"
)
# 獲取所有項(xiàng)目
projects = list(sonar.projects.search_projects())
# 獲取這個(gè)項(xiàng)目下最近一次分析任務(wù)的詳情
"""
componentKeys:某一個(gè)項(xiàng)目名稱
types:參數(shù)類型
CODE_SMELL==異常
BUG==bug
VULNERABILITY==漏洞
SECURITY_HOTSPOT==
"""
issues2 = list(sonar.issues.search_issues(componentKeys="python_s", types="CODE_SMELL"))通過metricKeys參數(shù)獲取這個(gè)項(xiàng)目中需要的值
# 參數(shù)1:component 項(xiàng)目名稱
# 參數(shù)2:metricKeys 想要獲取的某個(gè)值,逗號分割
component_data = sonar.measures.get_component_with_specified_measures(
component="python_test",
metricKeys="functions,classes"
)['component']['measures']
# 目前已收集的值和含義
'''
ncloc==總代碼長度
ncloc_language_distribution==其中每種語言的行數(shù)
bugs==bug數(shù)
vulnerabilities==漏洞數(shù)
code_smells==異常數(shù)
duplicated_lines_density==重復(fù)度百分比
coverage==代碼覆蓋率百分比
files==文件數(shù)量
functions==方法數(shù)量
classes==類數(shù)量
'''[root@localhost data]# cat wubo.py
#!/bin/python3
# encoding: utf-8
from sonarqube import SonarQubeClient
from operator import itemgetter
import json
import csv
import os
import time
import shutil
class SonarQube:
def __init__(self,url,username="admin",password="123456aA") -> None:
username = username
password = password
sonarqube_url = url
self.client = SonarQubeClient(username = username,password = password,sonarqube_url = sonarqube_url)
def getProjects(self):
"""獲取項(xiàng)目列表"""
projects = self.client.projects.search_projects().get("components")
return projects
def getIssues(self,jettech_project_name,issues_type):
"""獲取項(xiàng)目問題列表"""
#projects = self.client.issues.search_issues(componentKeys="jettoloader-pressurecommon",types="BUG",s="FILE_LINE",resolved="false",ps=1,organization="default-organization",facets="authors",additionalFields="_all")
projects = self.client.issues.search_issues(componentKeys=jettech_project_name,types=issues_type,s="FILE_LINE",resolved="false",ps=1,organization="default-organization",facets="authors",additionalFields="_all")
list_issues = projects["facets"][0]["values"]
#list_issues_name_count = []
#for list_issues_item in list_issues:
# list_issues_name_count.append(list_issues_item["val"])
# list_issues_name_count.append(list_issues_item["count"])
#print(list_issues)
#list_issues[0]["val"])
#list_issues[0]["count"])
return list_issues
def getMessages(self,component):
""" 獲取項(xiàng)目各個(gè)參數(shù)數(shù)據(jù)"""
#metricKeys = "alert_status,bugs,,vulnerabilities,security_rating,code_smells,duplicated_lines_density,coverage,ncloc"
metricKeys = "bugs,,vulnerabilities"
messages = []
messages.append(self.client.measures.get_component_with_specified_measures(component, metricKeys))
return messages[0]
def getMeasures(self,component,message):
measures = []
measures.insert(0,component)
measures_all = message.get("component").get("measures")
for measure_item in measures_all:
measures_type = measure_item.get("metric")
if "bugs" == measures_type:
measures.insert(1,measure_item.get("value"))
if "vulnerabilities" == measures_type:
measures.insert(2,measure_item.get("value"))
return measures
class CSV:
def __init__(self,filepath,filename) -> None:
self.filepath = filepath
self.filename = filename
def csv_write(self,project_measure_all):
#header = ['1project_name','2bugs','3vulnerabilities']
with open(self.filepath+"/"+self.filename, 'a') as file_obj:
writer = csv.writer(file_obj)
#writer.writerow(header)
for p in project_measure_all:
writer.writerow(p)
def csv_sort(self):
datas=[]
with open(self.filepath+"/"+self.filename, 'r') as f:
table = []
for line in f:
line = line.replace("\n","").replace("\r","")
col = line.split(',')
col[0] = str(col[0])
col[1] = col[1].strip("\n")
table.append(col)
table_sorted = sorted(table, key=itemgetter(0), reverse=False) # 精確的按照第1列排序
for row in table_sorted:
datas.append(row)
f.close()
with open(self.filepath+"/"+self.filename,"w", newline='') as csvfile:
writer = csv.writer(csvfile)
for data in datas:
writer.writerow(data)
csvfile.close()
def csv_insert(self):
header = 'project_name,bugs,vulnerabilities'
with open(self.filepath+"/"+self.filename, 'r+', encoding='utf-8') as f:
content = f.read()
f.seek(0, 0)
f.write(header + '\n' + content)
f.close()
def csv_delete(self):
if (os.path.exists(self.filepath)):
shutil.rmtree(self.filepath,ignore_errors=True)
def csv_sum(self):
with open(self.filepath+"/"+self.filename) as fin:
readline_item=fin.readline()
total_bug_api = 0
total_bug_manager = 0
total_bug_loader = 0
total_bug_ui = 0
total_vulnerabilities_api = 0
total_vulnerabilities_manager = 0
total_vulnerabilities_loader = 0
total_vulnerabilities_ui = 0
for row in csv.reader(fin):
row_project_name=row[0].split("-")[0]
if "jettoapi" == row_project_name:
total_bug_api += int(row[1])
total_vulnerabilities_api += int(row[2])
if "jettoloader" == row_project_name:
total_bug_loader += int(row[1])
total_vulnerabilities_loader += int(row[2])
if "jettomanager" == row_project_name:
total_bug_manager += int(row[1])
total_vulnerabilities_manager += int(row[2])
if "jettoui" == row_project_name:
total_bug_ui += int(row[1])
total_vulnerabilities_ui += int(row[2])
fin.close()
header_kong = ['','','']
header_api = ['jettoapi','bug總數(shù)',str(total_bug_api),'vulnerabilities總數(shù)',str(total_vulnerabilities_api)]
header_loader = ['jettoloader','bug總數(shù)',str(total_bug_loader),'vulnerabilities總數(shù)',str(total_vulnerabilities_loader)]
header_manager = ['jettomanager','bug總數(shù)',str(total_bug_manager),'vulnerabilities總數(shù)',str(total_vulnerabilities_manager)]
header_ui = ['jettoui','bug總數(shù)',str(total_bug_ui),'vulnerabilities總數(shù)',str(total_vulnerabilities_ui)]
with open(self.filepath+"/"+self.filename, 'a') as file_obj:
writer = csv.writer(file_obj)
writer.writerow(header_kong)
writer.writerow(header_api)
writer.writerow(header_loader)
writer.writerow(header_manager)
writer.writerow(header_ui)
file_obj.close()
class SCP:
def __init__(self,localdir,remoteip,remotedir) -> None:
self.localdir = localdir
self.remoteip = remoteip
self.remotedir = remotedir
def scp_operate(self):
os.system('scp -r "%s" "%s:%s"' % (self.localdir, self.remoteip, self.remotedir))
def main():
sonarQube = SonarQube(url='http://172.16.10.1:9000/')
all_project_info = sonarQube.getProjects()
project_measure_all=[]
project_issues_all=[]
for project_info in all_project_info:
component = project_info.get("key")
message = sonarQube.getMessages(component)
measure = sonarQube.getMeasures(component,message)
project_issues=[]
list_issues_s = sonarQube.getIssues(component,"BUG")
project_issues.append(component)
for list_issues_s_item in list_issues_s:
project_issues.append(list_issues_s_item["val"])
project_issues.append(list_issues_s_item["count"])
project_measure_all.extend([tuple(measure)])
project_issues_all.extend([tuple(project_issues)])
print([tuple(measure)])
#print(project_issues_all)
filepath=time.strftime("%Y-%m-%d")
filename="jettech_sornar_"+filepath+"_projects.csv"
filename_isuess="jettech_sornar_"+filepath+"_projects_iseuss.csv"
if not os.path.exists(filepath):
os.makedirs(filepath)
if os.path.exists(filepath+"/"+filename):
os.remove(filepath+"/"+filename)
if os.path.exists(filepath+"/"+filename_isuess):
os.remove(filepath+"/"+filename_isuess)
csv_obj = CSV(filepath=filepath,filename=filename)
csv_obj_isuess = CSV(filepath=filepath,filename=filename_isuess)
csv_obj.csv_write(project_measure_all)
csv_obj_isuess.csv_write(project_issues_all)
csv_obj.csv_sort()
csv_obj.csv_insert()
csv_obj.csv_sum()
localdir=filepath
remoteip="192.168.1.99"
remotedir="/product/gohttpserver/data/sornar/"
scp_obj = SCP(localdir,remoteip,remotedir)
scp_obj.scp_operate()
csv_obj.csv_delete()
if __name__== "__main__" :
main()到此這篇關(guān)于Python實(shí)現(xiàn)獲取sonarqube數(shù)據(jù)的文章就介紹到這了,更多相關(guān)Python獲取sonarqube數(shù)據(jù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python時(shí)間和字符串轉(zhuǎn)換操作實(shí)例分析
這篇文章主要介紹了Python時(shí)間和字符串轉(zhuǎn)換操作,結(jié)合實(shí)例形式分析了Python時(shí)間的格式化輸出、時(shí)間戳轉(zhuǎn)換、datetime轉(zhuǎn)換字符串等相關(guān)操作技巧,需要的朋友可以參考下2019-03-03
Python實(shí)現(xiàn)將Markdown文檔轉(zhuǎn)為EPUB電子書文件
這篇文章主要為大家詳細(xì)介紹了Python如何實(shí)現(xiàn)將Markdown文檔轉(zhuǎn)為EPUB電子書文件,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解一下2023-06-06
Python開發(fā)WebService系列教程之REST,web.py,eurasia,Django
對于今天的WebService開發(fā),我們至少有兩種選擇:SOAP/WSDL/UDDI系列的; REST風(fēng)格架構(gòu)系列的 ?。?!2014-06-06
Python實(shí)現(xiàn)12種降維算法的示例代碼
數(shù)據(jù)降維算法是機(jī)器學(xué)習(xí)算法中的大家族,與分類、回歸、聚類等算法不同,它的目標(biāo)是將向量投影到低維空間,以達(dá)到某種目的如可視化,或是做分類。本文將利用Python實(shí)現(xiàn)12種降維算法,需要的可以參考一下2022-04-04
使用Python實(shí)現(xiàn)多功能課堂點(diǎn)名器與抽簽工具
這篇文章主要為大家詳細(xì)介紹了如何使用Python實(shí)現(xiàn)多功能課堂點(diǎn)名器,也可以用作抽簽工具,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-02-02
python實(shí)現(xiàn)Virginia無密鑰解密
這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)Virginia無密鑰解密,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-03-03

