1.需求:每次Sonqube檢查完畢後,須要登錄才能看到結果沒法經過Jenkins發佈後直接看到bug 及漏洞數量。json
2.demo:發佈後,能夠將該項目的檢測結果簡單打印出來顯示,後面還能夠集成釘釘發送到羣裏。api
1 # -*- coding: UTF-8 -*- 2 import sys 3 reload(sys) 4 sys.setdefaultencoding('utf8') 5 6 ''' 7 @author:jmmei 8 @file: SonarQubeDingtalk.py 9 @time: 2019/7 10 ''' 11 import requests,json,jenkins,os,time,datetime 12 13 14 15 16 #經過jenkins變量JOB_NAME傳入第一個參數projectName 17 18 projectName=sys.argv[1] 19 20 def notification(projectName): 21 # sonar API 22 sonar_Url = 'http://www.baidu.com:9000/sonar/api/measures/search?projectKeys='+ projectName +'&metricKeys=alert_status%2Cbugs%2Creliability_rating%2Cvulnerabilities%2Csecurity_rating%2Ccode_smells%2Csqale_rating%2Cduplicated_lines_density%2Ccoverage%2Cncloc%2Cncloc_language_distribution' 23 resopnse = requests.get(sonar_Url).text 24 result = json.loads(resopnse) 25 bug = 0 26 leak = 0 27 code_smell = 0 28 coverage = 0 29 density = 0 30 status = '' 31 statusStr = '' 32 33 for item in result['measures']: 34 if item['metric']=="bugs": 35 bug = item['value'] 36 elif item['metric']=="vulnerabilities": 37 leak = item['value'] 38 elif item['metric']=='code_smells': 39 code_smell = item['value'] 40 elif item['metric']=='coverage': 41 coverage = item['value'] 42 elif item['metric']=='duplicated_lines_density': 43 density = item['value'] 44 elif item['metric']=='alert_status': 45 status = item['value'] 46 else: 47 pass 48 49 if status == 'ERROR': 50 messageUrl = 'http://www.iconsdb.com/icons/preview/soylent-red/x-mark-3-xxl.png' 51 statusStr = '失敗' 52 elif status == 'OK': 53 statusStr = '成功' 54 messageUrl = 'http://icons.iconarchive.com/icons/paomedia/small-n-flat/1024/sign-check-icon.png' 55 56 code_reslut= "Bug數:" + bug + "個," + \ 57 "漏洞數:" + leak + "個," + \ 58 "可能存在問題代碼:"+ code_smell + "行," + \ 59 "覆蓋率:" + coverage + "%," + \ 60 "重複率:" + density + "%" 61 print("靜態代碼掃描統計:"+"狀態:"+ status +","+code_reslut) 62 if int(bug)>=3: 63 print("bug 數量太多,請儘快修復再發布項目!") 64 sys.exit(1) 65 else: 66 print("代碼質量很是好") 67 68 69 70 71 if __name__=="__main__": 72 #sonarQube刷新結果 73 #time.sleep(10) 74 notification(projectName) 75