Use hostname infor instead of users list
[remote-debug.git] / board / suanzi-support
1 #!/usr/bin/env python2
2
3 from subprocess import call, Popen, PIPE, STDOUT, check_output
4 import paho.mqtt.client as mqtt
5 import shlex
6 import random
7 from uuid import getnode as get_mac
8 import ast
9 import sys
10 import re
11
12 MQTT_SERVER = 'mqtt.suanzi.ai'
13 MQTT_PORT = 1883
14
15 # The alive time new ssh session exist. It means if no client connect to this device through ssh tunnel in 5 minutes,
16 # this new sessin will terminate.
17 ALIVE_TIME = 60 * 5
18
19 SSH_SERVER = 'autossh.suanzi.ai'
20 PORT_RANGE = (20000, 40000)
21 USER = 'autossh'
22 PASSWORD = 'hard2guess'
23
24 def getAvailablePort(host, ports):
25     while True:
26         port = random.randint(ports[0], ports[1])
27         command = 'nc -z -v -w3 ' + host + ' ' + str(port)
28         p = Popen(command, shell=True, stdout=PIPE, stderr=STDOUT)
29         pout = p.communicate()[0].strip()
30         if p.returncode == 0:
31             continue
32         if 'Connection refused' in pout:
33             return port
34         else:
35             print pout
36
37 def get_mac_str():
38     mac = hex(get_mac())
39     m = re.sub('^0x|L$', '', mac)
40     return '{:0>12}'.format(m)
41
42 def get_hostname():
43     return check_output("/bin/hostname", shell=True).strip();
44
45 def exec_ssh(port):
46     if port == None:
47         raise Exception('Port not avaliable')
48     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)
49     print command
50     return call(shlex.split(command), shell=False)
51
52
53 def on_connect(client, userdata, flags, rc):
54     client.subscribe(userdata['id'])
55     client.subscribe('all')
56     print("Connected with result code "+str(rc))
57
58 def on_message(client, userdata, msg):
59     print('Receive topic:' + msg.topic + ' payload: ' +str(msg.payload))
60     payload = ast.literal_eval(str(msg.payload))
61     from_id = payload['from']
62     if payload['type'] == 'request':
63         if payload['command'] == 'ssh':
64             port = getAvailablePort(SSH_SERVER, PORT_RANGE)
65             if exec_ssh(port) == 0:
66                 response = {'from': userdata['id'], 'type':'response', 'command':payload['command'], 'data':port}
67                 client.publish(payload['from'], str(response))
68             else:
69                 raise Exception ('run ssh failed')
70         if payload['command'] == 'list':
71             response = {'from': userdata['id'], 'type':'response', 'command':payload['command'], 'data': get_hostname()}
72             client.publish(payload['from'], str(response))
73
74
75
76 if __name__ == '__main__':
77     id = get_mac_str()
78     print 'Mac: ', id
79     client = mqtt.Client(userdata={'id':id})
80     client.on_connect = on_connect
81     client.on_message = on_message
82     client.connect(MQTT_SERVER, MQTT_PORT, 60)
83     client.loop_forever()