前言
最近同事需要对所有的ibmmq通道消息数做个日均统计,于是就有了这个python脚本,然后再通过ansible这样子就批量获取到了。
脚本内容
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
pyhton ibmmq_count_conn_day.py
支持系统默认自带的python2.6运行.
命令参考:https://www.ibm.com/docs/zh/ibm-mq/8.0?topic=commands-display-chstatus-amqp
echo ' dis chstatus(conn) CHSTADA where(MSGS GT 0) ' |runmqsc 队列管理器名
"""
import datetime
import os
import re
import sys
def print_help():
print('Usage: ')
print('python ibmmq_count_conn_day.py queue_manager_name')
print('Example: python ibmmq_count_conn_day.py QML2_2')
def main():
if len(sys.argv) < 2:
print_help()
sys.exit(1)
# 获取参数
qmn_arg = sys.argv[1].upper()
# 当前时间
now_time = datetime.datetime.now()
cur_day = now_time.date()
# 每日总平均数
ave_num_day_total = 0
# 执行命令并读取输出
command = "echo ' dis chstatus(conn) CHSTADA where(MSGS GT 0) ' | /opt/mqm/bin/runmqsc \"%s\"" % qmn_arg
with os.popen(command) as f:
text = f.read()
if len(text) > 2:
lines = text.strip().split("Display Channel Status details.")
for line in lines:
# 确保不是空字符串
if line.strip():
chstada = re.search(r'CHSTADA\((.*?)\)', line)
msgs = re.search(r'MSGS\((\d+)\)', line)
# 打印提取的信息
if chstada and msgs:
pre_day = datetime.datetime.strptime(chstada.group(1), "%Y-%m-%d").date()
msgs_num = int(msgs.group(1))
time_difference_num = (cur_day - pre_day).days
if time_difference_num > 0:
ave_num_day = msgs_num / time_difference_num
ave_num_day_total += ave_num_day
elif time_difference_num == 0:
ave_num_day_total += msgs_num
print(qmn_arg + '日均统计量:' + str(ave_num_day_total))
if __name__ == "__main__":
main()