1
votes

currently I am trying to write a program that simulates an attack which yielded the following code:

import requests
import threading
import paho.mqtt.client as mqtt

class Attack(object):

    def __init__(self):

        self.client = mqtt.Client()
        self.client.on_connect = self.on_connect
        self.client.on_message = self.on_message

        self.client.connect("test.mosquitto.org")
        self.client.loop_forever()

    def poll_heise(self):
        while(True):
            time.sleep(2)
            r = requests.get('https://heise.de')

    def on_connect(self):
        self.client.subscribe("ATTACK")
        thread = threading.Thread(target=self.poll_heise)
        thread.start()

    def on_message(self):
        for i in range(1,80):
            thread = threading.Thread(target=self.write_file,args=(i,))
            thread.start()

    def write_file(self,suffix):
        new_file = open("file{0}".format(suffix),"w")
        new_file.write("testtesttesttest")
        new_file.close()


if __name__ == "__main__":
    attack = Attack()

Basically, what I want to do is to generate a distinctive behaviour that is maintained (e.g. polling heise.de with requests) and then disrupt this behaviour when an MQTT message on the topic "ATTACK" arrives.

However, when I start the code and try to trigger the on_message method by publishing to test.mosquitto.org on "ATTACK", I get nothing. As far as I know the interpreter doesn't even get to the on_message callback. I tried publishing and subscribing to the mqtt broker manually and it worked.

Anyone got ideas on why this does not work?

_ EDIT: I suspect that this is an issue with the way I handle the threads or some loop is blocking, but I can't identify which one it is. Many thanks in advance.

1

1 Answers

2
votes

The line self.client.loop_forever() is a blocking call, so your __init__ function will never return.

Looks at the client.start_loop() function instead.