Add script to add new user debug for remote debugging
[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 random
11 from uuid import getnode as get_mac
12
13 MQTT_SERVER = 'mqtt.suanzi.ai'
14 MQTT_PORT = 1883
15
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.
18 ALIVE_TIME = 60 * 5
19
20 SSH_SERVER = 'autossh.suanzi.ai'
21 PORT_RANGE = (20000, 40000)
22 USER = 'autossh'
23 PASSWORD = 'hard2guess'
24
25 def getAvailablePort(host, ports):
26     while True:
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()
31         if p.returncode == 0:
32             continue
33         if 'Connection refused' in pout:
34             return port
35         else:
36             print pout
37
38 def exec_ssh(port):
39     if port == None:
40         raise Exception('Port not avaliable')
41     command = 'sshpass -p' + PASSWORD + ' ssh -o "ServerAliveInterval 60" -o "ServerAliveCountMax 3" -fCR ' + str(port) +':localhost:22 ' + USER + '@' + SSH_SERVER + ' sleep ' + str(ALIVE_TIME)
42     print command
43     return call(shlex.split(command), shell=False)
44
45
46 def on_connect(client, userdata, flags, rc):
47     client.subscribe(client.id + '-request')
48     print("Connected with result code "+str(rc))
49
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)
57         else:
58             raise Exception ('run ssh failed')
59
60 class MyClient(mqtt.Client):
61     def __init__(self, id):
62         mqtt.Client.__init__(self)
63         self.id = id
64         self.on_connect = on_connect
65         self.on_message = on_message
66
67 if __name__ == '__main__':
68     mac = hex(get_mac())
69     id = '{:0>12}'.format(mac[2:-1])
70     print 'id is: ' , id
71     client = MyClient(id)
72     client.connect(MQTT_SERVER, MQTT_PORT, 60)
73     client.loop_forever()