4 # 1. pip install paho-mqtt
5 # 2. apt-get install sshpass
7 from subprocess import call, Popen, PIPE, STDOUT
8 import paho.mqtt.client as mqtt
11 from uuid import getnode as get_mac
14 MQTT_SERVER = 'mqtt.suanzi.zi'
18 SSH_SERVER = 'autossh.suanzi.ai'
19 PORT_RANGE = (20000, 20100)
21 PASSWORD = 'hard2guess'
23 def getAvailablePort(host, ports):
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()
31 if 'Connection refused' in pout:
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)
42 return call(shlex.split(command), shell=False)
44 def on_connect(client, userdata, flags, rc):
45 client.subscribe("rpdzkj-request")
46 print("Connected with result code "+str(rc))
48 def on_message(client, userdata, msg):
49 print(msg.topic+" "+str(msg.payload))
50 if msg.topic == 'rpdzkj-request':
51 print str(msg.payload)
52 port = getAvailablePort(SSH_SERVER, PORT_RANGE)
53 if exec_ssh(port) == 0:
54 client.publish('rpdzkj-response', port)
56 raise Exception ('run ssh failed')
58 if __name__ == '__main__':
59 client = mqtt.Client()
60 client.on_connect = on_connect
61 client.on_message = on_message
62 client.connect(MQTT_SERVER, MQTT_PORT, 60)