-
Notifications
You must be signed in to change notification settings - Fork 24
/
emulator.py
67 lines (43 loc) · 1.51 KB
/
emulator.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
"""
Emulator console module
"""
import socket
import re
import telnetlib
class ConsoleError(Exception): pass
class Console:
_AUTH_TOKEN_PATTERN = re.compile(r"'(.*\.emulator(?:_console)?_auth_token)'")
def __init__(self, host="127.0.0.1", port=5554):
self.emulator_telnet_host = host
self.emulator_telnet_port = port
self.sock = None
def connect(self):
try:
self.sock = telnetlib.Telnet(
self.emulator_telnet_host,
self.emulator_telnet_port,
1
)
reply = self.sock.read_until(b"OK", 1.0).decode("utf-8")
if not self._authenticate(reply):
raise ConsoleError("Emulator console authentication error")
except socket.error:
raise ConsoleError("Emulator console connection error")
def disconnect(self):
self.sock.close()
def send_cmd(self, cmd):
self.sock.write(f"{cmd}\n".encode())
return self.sock.read_until(b"OK", 60.0).decode("utf-8")
def _authenticate(self, reply):
token = Console._get_auth_token(reply)
if token is None:
return False
return "OK" in self.send_cmd(f"auth {token}")
@staticmethod
def _get_auth_token(reply):
result = Console._AUTH_TOKEN_PATTERN.search(reply)
if len(result.groups()) == 0:
return None
token_file = result.group(1)
with open(token_file, "r") as token_f:
return token_f.read().strip()