/
ammd.py
254 lines (206 loc) · 6.91 KB
/
ammd.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
#!/opt/anaconda/envs/mcserver/bin/python
from bottle import route, post, run, template, request, response, static_file, get, app, redirect
import random
from mcstatus import MinecraftServer
import psutil
import math
import socket
import re
import os
import time
import subprocess
import shlex
from beaker.middleware import SessionMiddleware
import hashlib
from binascii import hexlify
session_opts = {
'session.type': 'file',
'session.cookie_expires': False,
'session.data_dir': './data',
'session.auto': True
}
app_mw = SessionMiddleware(app(), session_opts)
PATH = "/home/minecraft/Techno"
LOGFILE = "logs/latest.log"
LOGFILTER = (
r"(/DEBUG)|"
r"(/TRACE)|"
r"(UUID of player)|"
r"(logged in with entity id)|"
r"(lost connection: TextComponent)"
)
server_status = None
server_status_time = None
STATUS_TIMEOUT = 45.0
CMDSTRING = r'screen -S FTB -p 0 -X stuff "{cmd}$(printf \\r)"'
SERVERSTART = r'/home/minecraft/Techno/start.sh'
def toSi(d, basis=1000):
incPrefixes = ['k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']
decPrefixes = ['m', 'µ', 'n', 'p', 'f', 'a', 'z', 'y']
if d < 0:
sign = "-"
d = math.fabs(d)
else:
sign = ""
ptr = -1
prefix = ""
if d > basis:
while d > basis:
ptr += 1
d = d / basis
if ptr >= 0:
prefix = incPrefixes[ptr]
else:
while d < (1/basis):
ptr += 1
d = d * basis
if ptr >= 0:
prefix = decPrefixes[ptr]
s = "{sign}{number:.2g} {prefix}".format(sign=sign, number=d, prefix=prefix)
return(s)
def sendCommand(cmd):
None
def getJavaProcess():
screenPid = subprocess.check_output("screen -list | grep FTB ", shell=True)
screenPid = int(re.search(r"^\t(\d+)\.", screenPid.decode("UTF-8", errors="replace")).group(1))
screenProcess = psutil.Process(screenPid)
return screenProcess.children()[0]
def getMCStats():
global server_status
global server_status_time
server = MinecraftServer("localhost", 25565)
try:
javaProcess = getJavaProcess()
query = server.query()
status = server.status()
except (subprocess.CalledProcessError, socket.gaierror, ConnectionRefusedError, BrokenPipeError, socket.timeout):
if server_status is not None:
return {"online": server_status}
else:
return {"online": "offline"}
javaMemory = javaProcess.memory_info().rss
javaMemory = toSi(javaMemory, 1024)
javaCPU = javaProcess.cpu_percent()
size = subprocess.check_output("du -sh {}".format(PATH), shell=True)
size_rx = re.search("^(.*?)(.)\t", size.decode("UTF-8", errors="replace"))
size = size_rx.group(1) + " " + size_rx.group(2)
resp = query.raw
resp["online"] = "online"
resp["players"] = query.players.names
resp["latency"] = status.latency
resp["minecraft_RAM"] = javaMemory
resp["minecraft_CPU"] = javaCPU
resp["minecraft_HDD"] = size
if server_status == "stopping":
resp["online"] = server_status
return resp
def getLog():
msg = []
with open(os.path.join(PATH, LOGFILE), encoding="UTF-8") as f:
for line in f.readlines():
if re.search(LOGFILTER, line): continue
msg.append(line)
return msg[-5:]
@route("/resources/<filepath:path>")
def serve_static(filepath):
return static_file(filepath, root = "resources")
@route('/login')
@post('/login')
def login():
session = request.environ.get('beaker.session')
username = request.forms.get('inputUsername')
password = request.forms.get('inputPassword')
if username is None and password is None:
return template("login")
else:
password = hexlify(hashlib.sha1(password.encode("ASCII")).digest()).decode("ASCII")
print("LoginUser:", username)
print("LoginPassword:", password)
with open("users") as f:
for line in f.readlines():
match = re.search("^(.*?)//(.*?)$", line)
user = match.group(1)
pwd = match.group(2)
print(user, pwd)
if user.lower() == username.lower() and pwd.lower() == password.lower():
session["username"] = username
session["online"] = True
break
else:
session["online"] = False
redirect("/")
@route('/logout')
def logout():
session = request.environ.get('beaker.session')
session["username"] = None
session["password"] = None
session["online"] = None
redirect("/")
@get('/favicon.ico')
def get_favicon():
return server_static('favicon.ico')
@route('/')
def index():
global server_status_time
global server_status
session = request.environ.get('beaker.session')
if server_status_time is not None:
if time.time() - server_status_time > STATUS_TIMEOUT:
server_status_time = None
server_status = None
mc = getMCStats()
# Only show commands when not remote
ip = request.remote_addr
if ip.startswith("127.0.0") or ip.startswith("192.168"):
local_client = True
else:
local_client = False
# Get CPU temperature
with open("/sys/class/thermal/thermal_zone2/temp") as f:
temperature = int(f.read())/1000
server_stats = {
"CPU": psutil.cpu_percent(percpu=False),
"CPU_temperature": temperature,
"CPU_cores": psutil.cpu_percent(percpu=True),
"RAM": [
psutil.virtual_memory().percent,
toSi(psutil.virtual_memory().total - psutil.virtual_memory().available, 1024),
toSi(psutil.virtual_memory().total, 1024),
],
"Disk": [
psutil.disk_usage(PATH).percent,
toSi(psutil.disk_usage(PATH).used),
toSi(psutil.disk_usage(PATH).free),
],
"log":getLog(),
"local_client": local_client,
"login": session.get("online"),
"username": session.get("username", None),
}
server_stats.update(mc)
return template("dashboard", stats=server_stats)
@post('/action')
def action():
global server_status
global server_status_time
action = request.json["action"]
msg = "OK"
if action == "start":
server_status = "starting"
server_status_time = time.time()
subprocess.call(SERVERSTART, shell=True)
elif action == "stop":
server_status = "stopping"
server_status_time = time.time()
subprocess.call(CMDSTRING.format(cmd="/stop"), shell=True)
elif action == "kill":
javaProcess = getJavaProcess()
javaProcess.kill()
elif action == "Command":
command = request.json["command"]
subprocess.call(CMDSTRING.format(cmd=command), shell=True)
else:
response.status = 404
msg = "Action not supported"
return(msg)
run(app=app_mw, host='', port=8080, debug = True)