forked from barneygale/MCRcon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmcrcon.py
55 lines (43 loc) · 1.68 KB
/
mcrcon.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
import socket
import select
import struct
import re
class MCRcon:
def __init__(self, host, port, password):
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.s.connect((host, port))
self.send_real(3, password)
def close(self):
self.s.close()
def send(self, command):
return self.send_real(2, command)
def send_real(self, out_type, out_data):
#Send the data
buff = struct.pack('<iii',
10+len(out_data),
0,
out_type) + out_data + "\x00\x00"
self.s.send(buff)
#Receive a response
in_data = ''
ready = True
while ready:
#Receive an item
tmp_len, tmp_req_id, tmp_type = struct.unpack('<iii', self.s.recv(12))
tmp_data = self.s.recv(tmp_len-8) #-8 because we've already read the 2nd and 3rd integer fields
#Error checking
if tmp_data[-2:] != '\x00\x00':
raise Exception('protocol failure', 'non-null pad bytes')
tmp_data = tmp_data[:-2]
#if tmp_type != out_type:
# raise Exception('protocol failure', 'type mis-match', tmp_type, out_type)
if tmp_req_id == -1:
raise Exception('auth failure')
m = re.match('^Error executing: %s \((.*)\)$' % re.escape(out_data), tmp_data)
if m:
raise Exception('command failure', m.group(1))
#Append
in_data += tmp_data
#Check if more data ready...
ready = select.select([self.s], [], [], 0)[0]
return in_data