3 from subprocess import call, Popen, PIPE, STDOUT
4 import paho.mqtt.client as mqtt
7 from uuid import getnode as get_mac
9 MQTT_SERVER = 'mqtt.suanzi.ai'
12 # The alive time new ssh session exist. It means if no client connect to this device through ssh tunnel in 5 minutes,
13 # this new sessin will terminate.
16 SSH_SERVER = 'autossh.suanzi.ai'
17 PORT_RANGE = (20000, 40000)
19 PASSWORD = 'hard2guess'
21 def getAvailablePort(host, ports):
23 port = random.randint(ports[0], ports[1])
24 command = 'nc -z -v -w3 ' + host + ' ' + str(port)
25 p = Popen(command, shell=True, stdout=PIPE, stderr=STDOUT)
26 pout = p.communicate()[0].strip()
29 if 'Connection refused' in pout:
36 raise Exception('Port not avaliable')
37 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)
39 return call(shlex.split(command), shell=False)
42 def on_connect(client, userdata, flags, rc):
43 client.subscribe(client.id + '-request')
44 print("Connected with result code "+str(rc))
46 def on_message(client, userdata, msg):
47 print(msg.topic+" "+str(msg.payload))
48 if msg.topic == client.id + '-request':
49 print str(msg.payload)
50 port = getAvailablePort(SSH_SERVER, PORT_RANGE)
51 if exec_ssh(port) == 0:
52 client.publish(client.id + '-response', port)
54 raise Exception ('run ssh failed')
56 class MyClient(mqtt.Client):
57 def __init__(self, id):
58 mqtt.Client.__init__(self)
60 self.on_connect = on_connect
61 self.on_message = on_message
63 if __name__ == '__main__':
65 id = '{:0>12}'.format(mac[2:-1])
68 client.connect(MQTT_SERVER, MQTT_PORT, 60)