Add install file
[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 ALIVE_TIME = 60 * 5
17
18 SSH_SERVER = 'autossh.suanzi.ai'
19 PORT_RANGE = (20000, 30000)
20 USER = 'autossh'
21 PASSWORD = 'hard2guess'
22
23 def getAvailablePort(host, ports):
24     while True:
25         port = random.randint(ports[0], ports[1])
26         command = 'nc -z -v -w5 ' + host + ' ' + str(port)
27         p = Popen(command, shell=True, stdout=PIPE, stderr=STDOUT)
28         pout = p.communicate()[0].strip()
29         if p.returncode == 0:
30             continue
31         if 'Connection refused' in pout:
32             return port
33         else:
34             print pout
35
36 def exec_ssh(port):
37     if port == None:
38         raise Exception('Port not avaliable')
39     #command = 'sshpass -p' + PASSWORD + ' ssh -o "ServerAliveInterval 30" -o "ServerAliveCountMax 1" -fCNR ' + str(port) +':localhost:22 ' + USER + '@' + SSH_SERVER
40     command = 'sshpass -p' + PASSWORD + ' ssh -o "ServerAliveInterval 60" -o "ServerAliveCountMax 3" -fCR ' + str(port) +':localhost:22 ' + USER + '@' + SSH_SERVER + ' sleep ' + str(ALIVE_TIME)
41     print command
42     return call(shlex.split(command), shell=False)
43
44
45 def on_connect(client, userdata, flags, rc):
46     #client.subscribe("rpdzkj-request")
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 = os.getenv('USER') + '-' + '{:0>12}'.format(mac[2:13])
70     print 'id is: ' , id
71     client = MyClient(id)
72     client.connect(MQTT_SERVER, MQTT_PORT, 60)
73     client.loop_forever()