3 from subprocess import call, Popen, PIPE, STDOUT
4 import paho.mqtt.client as mqtt
7 from uuid import getnode as get_mac
11 MQTT_SERVER = 'mqtt.suanzi.ai'
14 # The alive time new ssh session exist. It means if no client connect to this device through ssh tunnel in 5 minutes,
15 # this new sessin will terminate.
18 SSH_SERVER = 'autossh.suanzi.ai'
19 PORT_RANGE = (20000, 40000)
21 PASSWORD = 'hard2guess'
23 def getAvailablePort(host, ports):
25 port = random.randint(ports[0], ports[1])
26 command = 'nc -z -v -w3 ' + host + ' ' + str(port)
27 p = Popen(command, shell=True, stdout=PIPE, stderr=STDOUT)
28 pout = p.communicate()[0].strip()
31 if 'Connection refused' in pout:
38 return '{:0>12}'.format(mac[2:-1])
42 raise Exception('Port not avaliable')
43 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)
45 return call(shlex.split(command), shell=False)
48 def on_connect(client, userdata, flags, rc):
49 client.subscribe(userdata['id'])
50 client.subscribe('all')
51 print("Connected with result code "+str(rc))
53 def on_message(client, userdata, msg):
54 print('Receive topic:' + msg.topic + ' payload: ' +str(msg.payload))
55 payload = ast.literal_eval(str(msg.payload))
56 from_id = payload['from']
57 if payload['type'] == 'request':
58 if payload['command'] == 'ssh':
59 port = getAvailablePort(SSH_SERVER, PORT_RANGE)
60 if exec_ssh(port) == 0:
61 response = {'from': userdata['id'], 'type':'response', 'command':payload['command'], 'data':port}
62 client.publish(payload['from'], str(response))
64 raise Exception ('run ssh failed')
65 if payload['command'] == 'list':
66 response = {'from': userdata['id'], 'type':'response', 'command':payload['command'], 'data':'OK'}
67 client.publish(payload['from'], str(response))
71 if __name__ == '__main__':
74 client = mqtt.Client(userdata={'id':id})
75 client.on_connect = on_connect
76 client.on_message = on_message
77 client.connect(MQTT_SERVER, MQTT_PORT, 60)