重要提示!!!
- 本教程针对JAVA服务器,基岩版请回
- 教程中的环境是Mohist1.19.4,命令可能与其他版本不同,请自行修改
食用方法
1.开启RCON
什么是RCON呢?RCON就是一种远程执行MC命令的协议。但是出于安全考虑,它默认关闭,我们要在server.properties
中配置一下
- enable-rcon 的意思是启用RCON,我们把它设成true
- rcon.port 是RCON的端口,默认25575,记得让防火墙放行
- rcon.password 是RCON的密码,不能为空
做完了以上操作,就重启一下,看到“RCON running on 0.0.0.0:25575”的字样就代表成功啦
2.开发
代码如下,记得安装一下mcrcon和psutil
from mcrcon import MCRcon
import subprocess as sp
import psutil,time
def main():
# 这里把password改成你的密码
with MCRcon("127.0.0.1", "password") as mcr:
mcr.command("say 连接成功")
while True:
# 获取内存占用、CPU占用、CPU温度
ram = int(psutil.virtual_memory().used / psutil.virtual_memory().total * 100)
cpu = int(psutil.cpu_percent(interval=0))
cpu_temp = int(int(str(sp.run("cat /sys/class/thermal/thermal_zone0/temp", shell=True, stdout=sp.PIPE).stdout, encoding = "gbk"))/1000)
while cpu == 0:
cpu = psutil.cpu_percent(interval=0.01) * 2
# 使所有玩家可见
mcr.command('bossbar set cpu players @a')
mcr.command('bossbar set ram players @a')
# 根据占用调整颜色
if ram > 80:
mcr.command("bossbar set minecraft:ram color red")
elif ram > 40:
mcr.command("bossbar set minecraft:ram color yellow")
else:
mcr.command("bossbar set minecraft:ram color green")
# 更新到标题和值
mcr.command(f'bossbar set minecraft:ram name "内存 {ram}%"')
mcr.command(f"bossbar set minecraft:ram value {ram}")
# 根据占用调整颜色
if cpu > 80:
mcr.command("bossbar set minecraft:cpu color red")
elif cpu > 40:
mcr.command("bossbar set minecraft:cpu color yellow")
else:
mcr.command("bossbar set minecraft:cpu color green")
# 更新到标题和值
mcr.command(f'bossbar set minecraft:cpu name "CPU {cpu}% {cpu_temp}°C"')
mcr.command(f"bossbar set minecraft:cpu value {cpu}")
def try_main():
# 尝试运行
try:
main()
except:
# 若报错则10秒后重连
for i in range(10, 0, -1):
print(f"无法连接,{i}秒后重连")
time.sleep(1)
try_main()
if __name__ == "__main__":
try_main()
3.自启动配置 & 一些命令
sudo nano /etc/rc.local
把/usr/bin/python /xxx/xxx/xxx.py &
添加到exit 0
前
开服执行以下命令,根据情况加/
/bossbar add cpu ""
/bossbar add ram ""
4.完成
重启开服看看效果吧!