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