A mqtt sniffer
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import argparse
  2. from console_bottombar import BottomBar
  3. import getpass
  4. import json
  5. import mqtt
  6. import os
  7. import re
  8. import time
  9. VERSION = "0.1.0"
  10. STARTTIME = time.time()
  11. HELPTEXT = """
  12. F1: Get this help message
  13. F2: Set a filter (regular expression) for the topic of a message
  14. Examples:
  15. * "/gfw/.*/main_light/" to get everything with "/gfw/" before "/main_light/"
  16. * "^zigbee.*(?>!logging)$" to get everything starting with "zigbee" and not ending with "logging"
  17. * "^(?!shellies).*/dirk/.*temperature$" to get everything not starting with "shellies" followed by "/dirk/" and ends with "temperature"
  18. F9: Start / Stop logging to mqtt-sniffer.log
  19. F12: Quit the mqtt sniffer
  20. 'c': Clear screen
  21. 'q': Quit
  22. """
  23. def rx_mqtt(mc, userdata, message):
  24. global my_bb
  25. global logfile
  26. try:
  27. match = len(re.findall(my_bb.get_entry('msg_re'), message.topic)) > 0
  28. except re.error:
  29. print('No valid regular expression (%s). No filter active.' % my_bb.get_entry('msg_re'))
  30. match = True
  31. ts = time.time()-STARTTIME
  32. data = None
  33. try:
  34. data = json.loads(message.payload)
  35. except:
  36. pass
  37. try:
  38. data = message.payload.decode("utf-8")
  39. except:
  40. data = message.payload
  41. if match:
  42. print("%9.04f::%75s::%s" % (ts, message.topic, data))
  43. if my_bb.get_entry('log2file'):
  44. logfile.write("%9.04f::%s::%s\n" % (ts, message.topic, data))
  45. logfile.flush()
  46. if __name__ == "__main__":
  47. parser = argparse.ArgumentParser(description='This is a mqtt sniffer.')
  48. parser.add_argument('-f', dest='hostname', default='localhost', help='Hostname of the mqtt server')
  49. parser.add_argument('-p', dest='port', default=1883, help='Port of the mqtt server')
  50. parser.add_argument('-n', dest='no_credentials', action='store_true', help='Avoid asking for credentials')
  51. parser.add_argument('-u', dest='username', default=None, help='Set username for mqtt server')
  52. parser.add_argument('-t', dest='topicfilter', default="", help='Set topic filter')
  53. parser.add_argument('-l', dest='logtofile', action='store_true', help='Enable logging to file')
  54. args = parser.parse_args()
  55. if not args.no_credentials:
  56. if args.username == None:
  57. args.username = input("Username: ")
  58. password = getpass.getpass(prompt='Password: ', stream=None)
  59. else:
  60. args.username = None
  61. password = None
  62. my_bb = BottomBar(VERSION, label='MQTT-Sniffer')
  63. my_bb.add_entry('help', 1, my_bb.FUNC_INFO, label='[F1] Help', infotext=HELPTEXT)
  64. my_bb.add_entry('msg_re', 2, my_bb.FUNC_TEXT, label='[F2] Filter', default=args.topicfilter)
  65. my_bb.add_entry('quit', 12, my_bb.FUNC_QUIT, "Quit", label='[F12]', right=True)
  66. my_bb.add_entry('log2file', 9, my_bb.FUNC_BOOL, label='[F9] Log2File', default=args.logtofile, right=True)
  67. with open('mqtt_sniffer.log', 'w') as logfile:
  68. mc = mqtt.mqtt_client("mqtt_sniffer", args.hostname, port=args.port, username=args.username, password=password)
  69. mc.add_callback("#", rx_mqtt)
  70. my_bb.run()