Skip to content

Instantly share code, notes, and snippets.

@Reelix
Created March 10, 2023 10:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Reelix/e9132639937446ad0489b81a451c70ab to your computer and use it in GitHub Desktop.
Save Reelix/e9132639937446ad0489b81a451c70ab to your computer and use it in GitHub Desktop.
A MQTT client that connects using MQTTv31, MQTTv311, MQTTv5 simultaneously and subscribes to every topic.
# https://shamsher-khan.medium.com/broker-tryhackme-writeup-93202a3f778
# https://pypi.org/project/paho-mqtt/#client
import paho.mqtt.client as mqtt
import threading
import sys
import ipaddress
IP = ""
try:
ipaddress.ip_address(sys.argv[1])
IP = sys.argv[1]
except:
print("Invalid IP address: python3 mqtt_multiclient.py 127.0.0.1")
exit(0);
class thread(threading.Thread):
def __init__(self, thread_name, thread_protocol, thread_ID):
threading.Thread.__init__(self)
self.thread_name = thread_name
self.thread_protocol = thread_protocol
self.thread_ID = thread_ID
def run(self):
client = mqtt.Client(protocol=self.thread_protocol)
client.on_connect = on_connect
client.on_message = on_message
print("Connecting to " + str(IP) + " with " + str(self.thread_name) + " and listening...")
try:
client.connect(IP, 1883, 60)
client.loop_forever()
except:
print("Nope - Something broke")
def on_connect(client, userdata, flags, rc):
print("Successfully connected!")
client.subscribe("#")
def on_message(client, userdata, msg):
print("[" + msg.topic + "] " + str(msg.payload.decode()))
thread1 = thread("v31", mqtt.MQTTv31, 1000)
thread2 = thread("v311", mqtt.MQTTv311, 2000)
thread3 = thread("v5", mqtt.MQTTv5, 3000)
thread1.start();
thread2.start();
thread3.start();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment