DingDing.py 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import os
  2. import socket
  3. from pathlib import Path
  4. from dingtalkchatbot.chatbot import DingtalkChatbot
  5. import datetime
  6. # 获取jenkins构建信息和本次报告地址
  7. import jenkins # 安装pip install python-jenkins
  8. from common.yaml_util import read_config_yaml, read_yaml_out_time_url, write_yaml_out_time_url
  9. # 获取本机IP
  10. s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  11. # s.connect(("8.8.8.8", 80))
  12. # ip = s.getsockname()[0]
  13. # jenkins登录地址
  14. jenkins_url = "http://121.229.175.82:63222/"
  15. # 获取jenkins对象
  16. server = jenkins.Jenkins(jenkins_url, username='jiangwei', password='jW@123456') # Jenkins登录名 ,密码
  17. # job名称
  18. job_name = "job/XCHY/" # Jenkins运行任务名称
  19. # job的url地址
  20. job_url = jenkins_url + job_name
  21. # 获取最后一次构建
  22. job_last_build_url = server.get_info(job_name)['lastBuild']['url']
  23. # 报告地址
  24. report_url = job_last_build_url + 'allure' # 'allure'为我的Jenkins全局工具配置中allure别名
  25. if "localhost" in report_url:
  26. report_url = report_url.replace("localhost", ip)
  27. else:
  28. report_url = report_url
  29. '''
  30. 钉钉推送方法:
  31. 读取report文件中"prometheusData.txt",循环遍历获取需要的值。
  32. 使用钉钉机器人的接口,拼接后推送text
  33. '''
  34. # url = 'https://oapi.dingtalk.com/robot/send?access_token=f8566d2ed0feb8dc3bf2856df161241a8cf5a4c76af3d903abcabfdebebdff0e' # webhook
  35. text1 = (
  36. f"<font color=\'#FFA500\'>[通知] </font>星辰绘影-服务巡检"
  37. "\n\n服务巡检情况: " + "正常" +
  38. "\n\n播报时间: " + datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
  39. text2 = (
  40. f"<font color=\'#FFA500\'>[通知] </font>星辰绘影-服务巡检"
  41. '''\n\n<font>服务巡检情况: </font><font color=\'#FF0000\' size=2>异常</font> \n\n''' +
  42. "\n\n播报时间: " + datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
  43. def DingTalkSend(text1, text2):
  44. d = {}
  45. # 获取项目绝对路径
  46. path = Path(__file__).parent
  47. file = '/report/export/prometheusData.txt'
  48. print(rf"{path}" + rf"{file}")
  49. # 打开prometheusData 获取需要发送的信息
  50. # f = open(rf"{path}" + rf"{file}", 'r', encoding='UTF-8')
  51. f = open(os.getcwd() + file, 'r', encoding='UTF-8')
  52. for lines in f:
  53. for c in lines:
  54. launch_name = lines.strip('\n').split(' ')[0]
  55. num = lines.strip('\n').split(' ')[1]
  56. d.update({launch_name: num})
  57. print(d)
  58. f.close()
  59. status_failed = d.get('launch_status_broken') # 不通过数量
  60. print('不通过数量:{}'.format(status_failed))
  61. # 钉钉推送
  62. print(type(status_failed))
  63. dd_robot = DingtalkChatbot(read_config_yaml("dingding", "prod_webhook"))
  64. if status_failed == "0":
  65. dd_robot.send_markdown(title='星辰绘影服务巡检', text=text1, is_at_all=False)
  66. else:
  67. dd_robot.send_markdown(title='星辰绘影服务巡检', text=text2, is_at_all=False)
  68. if __name__ == '__main__':
  69. DingTalkSend( text1, text2)