update install.sh
[remote-debug.git] / suanzi-support
1 #!/usr/bin/env python2
2
3 # dependencies:
4 #   1. pip install paho-mqtt
5 #   2. apt-get install sshpass
6 #
7 from subprocess import call, Popen, PIPE, STDOUT
8 import paho.mqtt.client as mqtt
9 import shlex
10 import os
11 import random
12 from uuid import getnode as get_mac
13
14 MQTT_SERVER = 'mqtt.suanzi.ai'
15 MQTT_PORT = 1883
16
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.
19 ALIVE_TIME = 60 * 5
20
21 SSH_SERVER = 'autossh.suanzi.ai'
22 PORT_RANGE = (20000, 40000)
23 USER = 'autossh'
24 PASSWORD = 'hard2guess'
25
26 def getAvailablePort(host, ports):
27     while True:
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()
32         if p.returncode == 0:
33             continue
34         if 'Connection refused' in pout:
35             return port
36         else:
37             print pout
38
39 def exec_ssh(port):
40     if port == None:
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)
43     print command
44     return call(shlex.split(command), shell=False)
45
46
47 def on_connect(client, userdata, flags, rc):
48     client.subscribe(client.id + '-request')
49     print("Connected with result code "+str(rc))
50
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)
58         else:
59             raise Exception ('run ssh failed')
60
61 class MyClient(mqtt.Client):
62     def __init__(self, id):
63         mqtt.Client.__init__(self)
64         self.id = id
65         self.on_connect = on_connect
66         self.on_message = on_message
67
68 if __name__ == '__main__':
69     mac = hex(get_mac())
70     id = os.getenv('USER') + '-' + '{:0>12}'.format(mac[2:13])
71     print 'id is: ' , id
72     client = MyClient(id)
73     client.connect(MQTT_SERVER, MQTT_PORT, 60)
74     client.loop_forever()