Skip to content

Commit

Permalink
Monitor multiple minecraft servers
Browse files Browse the repository at this point in the history
  • Loading branch information
vfuse committed Mar 8, 2018
1 parent d07593f commit bf36d32
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 40 deletions.
2 changes: 1 addition & 1 deletion nixstatsagent/nixstatsagent.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
import urllib2


__version__ = '1.1.40'
__version__ = '1.1.41'

__FILEABSDIRNAME__ = os.path.dirname(os.path.abspath(__file__))

Expand Down
82 changes: 43 additions & 39 deletions nixstatsagent/plugins/minecraft.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,47 +11,51 @@ def run(self, config):
Fetch the amount of active and max players
add to /etc/nixstats.ini
[minecraft]
enabled=yes
host=minecraft_host_or_IP
port=minecraft_PORT
enabled=yes
hosts=127.0.0.1:8000,127.0.0.2:8000...
'''

try:
# Connect
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = config.get('minecraft', 'host')
port = int(config.get('minecraft', 'port'))
s.connect((host, port))

# Send handshake + status request
s.send(self.pack_data("\x00\x00" + self.pack_data(host.encode('utf8')) + self.pack_port(port) + "\x01"))
s.send(self.pack_data("\x00"))

# Read response
self.unpack_varint(s) # Packet length
self.unpack_varint(s) # Packet ID
l = self.unpack_varint(s) # String length

d = ""
while len(d) < l:
d += s.recv(1024)

# Close our socket
s.close()
except:
return "Could not connect to server"

results = {}

try:
players = json.loads(d.decode('utf8'))['players']
results['online'] = int(players['online'])
results['max'] = int(players['max'])
except:
results['online'] = 0
results['max'] = 0

return results
my_hosts = config.get('minecraft', 'hosts').split(',')
result = {}
for connection_string in my_hosts:
try:
# Connect
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
hostname = connection_string.split(':')[0]
port = int(connection_string.split(':')[1])
s.connect((hostname, port))

# Send handshake + status request
s.send(self.pack_data("\x00\x00" + self.pack_data(hostname.encode('utf8')) + self.pack_port(port) + "\x01"))
s.send(self.pack_data("\x00"))

# Read response
self.unpack_varint(s) # Packet length
self.unpack_varint(s) # Packet ID
l = self.unpack_varint(s) # String length

d = ""
while len(d) < l:
d += s.recv(1024)

# Close our socket
s.close()
except:
pass

results = {}

try:
players = json.loads(d.decode('utf8'))['players']
results['online'] = int(players['online'])
results['max'] = int(players['max'])
except:
results['online'] = 0
results['max'] = 0
result[str(connection_string.replace('.', '-'))] = results

return result


def unpack_varint(self, s):
d = 0
Expand Down

0 comments on commit bf36d32

Please sign in to comment.