4 # 1. pip install paho-mqtt
5 # 2. apt-get install sshpass
7 from subprocess import call, Popen, PIPE, STDOUT
8 import paho.mqtt.client as mqtt
11 from uuid import getnode as get_mac
13 MQTT_SERVER = 'mqtt.suanzi.ai'
16 # The alive time new ssh session exist. It means if no client connect to this device through ssh tunnel in 5 minutes,
17 # this new sessin will terminate.
20 SSH_SERVER = 'autossh.suanzi.ai'
21 PORT_RANGE = (20000, 40000)
23 PASSWORD = 'hard2guess'
25 def getAvailablePort(host, ports):
27 port = random.randint(ports[0], ports[1])
28 command = 'nc -z -v -w3 ' + host + ' ' + str(port)
29 p = Popen(command, shell=True, stdout=PIPE, stderr=STDOUT)
30 pout = p.communicate()[0].strip()
33 if 'Connection refused' in pout:
40 raise Exception('Port not avaliable')
41 command = 'sshpass -p' + PASSWORD + ' ssh -o "StrictHostKeyChecking=no" -o "UserKnownHostsFile /dev/null" -o "ServerAliveInterval 60" -o "ServerAliveCountMax 3" -fCR ' + str(port) +':localhost:22 ' + USER + '@' + SSH_SERVER + ' sleep ' + str(ALIVE_TIME)
43 return call(shlex.split(command), shell=False)
46 def on_connect(client, userdata, flags, rc):
47 client.subscribe(client.id + '-request')
48 print("Connected with result code "+str(rc))
50 def on_message(client, userdata, msg):
51 print(msg.topic+" "+str(msg.payload))
52 if msg.topic == client.id + '-request':
53 print str(msg.payload)
54 port = getAvailablePort(SSH_SERVER, PORT_RANGE)
55 if exec_ssh(port) == 0:
56 client.publish(client.id + '-response', port)
58 raise Exception ('run ssh failed')
60 class MyClient(mqtt.Client):
61 def __init__(self, id):
62 mqtt.Client.__init__(self)
64 self.on_connect = on_connect
65 self.on_message = on_message
67 if __name__ == '__main__':
69 id = '{:0>12}'.format(mac[2:-1])
72 client.connect(MQTT_SERVER, MQTT_PORT, 60)