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
12 from uuid import getnode as get_mac
14 MQTT_SERVER = 'mqtt.suanzi.ai'
17 # The alive time new ssh session exist. It means if no client connect to this device through ssh tunnel in 5 minutes,
18 # this new sessin will terminate.
21 SSH_SERVER = 'autossh.suanzi.ai'
22 PORT_RANGE = (20000, 40000)
24 PASSWORD = 'hard2guess'
26 def getAvailablePort(host, ports):
28 port = random.randint(ports[0], ports[1])
29 command = 'nc -z -v -w3 ' + host + ' ' + str(port)
30 p = Popen(command, shell=True, stdout=PIPE, stderr=STDOUT)
31 pout = p.communicate()[0].strip()
34 if 'Connection refused' in pout:
41 raise Exception('Port not avaliable')
42 command = 'sshpass -p' + PASSWORD + ' ssh -o "ServerAliveInterval 60" -o "ServerAliveCountMax 3" -fCR ' + str(port) +':localhost:22 ' + USER + '@' + SSH_SERVER + ' sleep ' + str(ALIVE_TIME)
44 return call(shlex.split(command), shell=False)
47 def on_connect(client, userdata, flags, rc):
48 client.subscribe(client.id + '-request')
49 print("Connected with result code "+str(rc))
51 def on_message(client, userdata, msg):
52 print(msg.topic+" "+str(msg.payload))
53 if msg.topic == client.id + '-request':
54 print str(msg.payload)
55 port = getAvailablePort(SSH_SERVER, PORT_RANGE)
56 if exec_ssh(port) == 0:
57 client.publish(client.id + '-response', port)
59 raise Exception ('run ssh failed')
61 class MyClient(mqtt.Client):
62 def __init__(self, id):
63 mqtt.Client.__init__(self)
65 self.on_connect = on_connect
66 self.on_message = on_message
68 if __name__ == '__main__':
70 id = os.getenv('USER') + '-' + '{:0>12}'.format(mac[2:13])
73 client.connect(MQTT_SERVER, MQTT_PORT, 60)