This repository has been archived by the owner on Apr 18, 2020. It is now read-only.
forked from geekbeard/ServerStatsBot
-
Notifications
You must be signed in to change notification settings - Fork 2
/
servstatsbot.py
202 lines (187 loc) · 8.88 KB
/
servstatsbot.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
from tokens import *
import matplotlib
matplotlib.use("Agg") # has to be before any other matplotlibs imports to set a "headless" backend
import matplotlib.pyplot as plt
import psutil
from datetime import datetime
from subprocess import Popen, PIPE, STDOUT
import operator
import collections
# import sys
import time
# import threading
# import random
import telepot
# from telepot.namedtuple import ReplyKeyboardMarkup, KeyboardButton, ReplyKeyboardHide, ForceReply
# from telepot.namedtuple import InlineKeyboardMarkup, InlineKeyboardButton
# from telepot.namedtuple import InlineQueryResultArticle, InlineQueryResultPhoto, InputTextMessageContent
memorythreshold = 85 # If memory usage more this %
poll = 300 # seconds
shellexecution = []
timelist = []
memlist = []
xaxis = []
settingmemth = []
setpolling = []
graphstart = datetime.now()
stopmarkup = {'keyboard': [['Stop']]}
hide_keyboard = {'hide_keyboard': True}
def clearall(chat_id):
if chat_id in shellexecution:
shellexecution.remove(chat_id)
if chat_id in settingmemth:
settingmemth.remove(chat_id)
if chat_id in setpolling:
setpolling.remove(chat_id)
def plotmemgraph(memlist, xaxis, tmperiod):
# print(memlist)
# print(xaxis)
plt.xlabel(tmperiod)
plt.ylabel('% Used')
plt.title('Memory Usage Graph')
plt.text(0.1*len(xaxis), memorythreshold+2, 'Threshold: '+str(memorythreshold)+ ' %')
memthresholdarr = []
for xas in xaxis:
memthresholdarr.append(memorythreshold)
plt.plot(xaxis, memlist, 'b-', xaxis, memthresholdarr, 'r--')
plt.axis([0, len(xaxis)-1, 0, 100])
plt.savefig('/tmp/graph.png')
plt.close()
f = open('/tmp/graph.png', 'rb') # some file on local disk
return f
class YourBot(telepot.Bot):
def __init__(self, *args, **kwargs):
super(YourBot, self).__init__(*args, **kwargs)
self._answerer = telepot.helper.Answerer(self)
self._message_with_inline_keyboard = None
def on_chat_message(self, msg):
content_type, chat_type, chat_id = telepot.glance(msg)
# Do your stuff according to `content_type` ...
print("Your chat_id:" + str(chat_id)) # this will tell you your chat_id
if chat_id in adminchatid: # Store adminchatid variable in tokens.py
if content_type == 'text':
if msg['text'] == '/stats' and chat_id not in shellexecution:
bot.sendChatAction(chat_id, 'typing')
memory = psutil.virtual_memory()
disk = psutil.disk_usage('/')
boottime = datetime.fromtimestamp(psutil.boot_time())
now = datetime.now()
timedif = "在线时间: %.1f 小时" % (((now - boottime).total_seconds()) / 3600)
memtotal = "总内存: %.2f GB " % (memory.total / 1000000000)
memavail = "可用内存: %.2f GB" % (memory.available / 1000000000)
memuseperc = "使用内存: " + str(memory.percent) + " %"
diskused = "磁盘占用: " + str(disk.percent) + " %"
pids = psutil.pids()
pidsreply = ''
procs = {}
for pid in pids:
p = psutil.Process(pid)
try:
pmem = p.memory_percent()
if pmem > 0.5:
if p.name() in procs:
procs[p.name()] += pmem
else:
procs[p.name()] = pmem
except:
print("Hm")
sortedprocs = sorted(procs.items(), key=operator.itemgetter(1), reverse=True)
for proc in sortedprocs:
pidsreply += proc[0] + " " + ("%.2f" % proc[1]) + " %\n"
reply = timedif + "\n" + \
memtotal + "\n" + \
memavail + "\n" + \
memuseperc + "\n" + \
diskused + "\n\n" + \
pidsreply
bot.sendMessage(chat_id, reply, disable_web_page_preview=True)
elif msg['text'] == "help" or msg['text'] == "/help" or msg['text'] == "/start":
bot.sendMessage(chat_id, "以下命令可用")
bot.sendMessage(chat_id, "/stats -检查磁盘/CPU/内存使用情况")
bot.sendMessage(chat_id, "/shell -字面意思")
bot.sendMessage(chat_id, "/memgraph -绘制近一段时间的内存使用记录表")
bot.sendMessage(chat_id, "/setmem -设置内存占用告警阈值,并在占用情况高于这个值是告警")
bot.sendMessage(chat_id, "/setpoll -设置探测间隔(不少于10秒)")
bot.sendMessage(chat_id, "/stop -AZ5")
elif msg['text'] == "Stop":
clearall(chat_id)
bot.sendMessage(chat_id, "所有操作已经停止了", reply_markup=hide_keyboard)
elif msg['text'] == '/setpoll' and chat_id not in setpolling:
bot.sendChatAction(chat_id, 'typing')
setpolling.append(chat_id)
bot.sendMessage(chat_id, "发给我一个新的探测间隔(不少于10秒)", reply_markup=stopmarkup)
elif chat_id in setpolling:
bot.sendChatAction(chat_id, 'typing')
try:
global poll
poll = int(msg['text'])
if poll > 10:
bot.sendMessage(chat_id, "整好了!")
clearall(chat_id)
else:
1/0
except:
bot.sendMessage(chat_id, "需要大于等于10秒,再来一次")
elif msg['text'] == "/shell" and chat_id not in shellexecution:
bot.sendMessage(chat_id, "发给我一条命令以执行", reply_markup=stopmarkup)
shellexecution.append(chat_id)
elif msg['text'] == "/setmem" and chat_id not in settingmemth:
bot.sendChatAction(chat_id, 'typing')
settingmemth.append(chat_id)
bot.sendMessage(chat_id, "发给我一个新的内存占用告警阈值?", reply_markup=stopmarkup)
elif chat_id in settingmemth:
bot.sendChatAction(chat_id, 'typing')
try:
global memorythreshold
memorythreshold = int(msg['text'])
if memorythreshold < 100:
bot.sendMessage(chat_id, "整好了!")
clearall(chat_id)
else:
1/0
except:
bot.sendMessage(chat_id, "都说了要小于100啊")
elif chat_id in shellexecution:
bot.sendChatAction(chat_id, 'typing')
p = Popen(msg['text'], shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
output = p.stdout.read()
if output != b'':
bot.sendMessage(chat_id, output, disable_web_page_preview=True)
else:
bot.sendMessage(chat_id, "没有输出", disable_web_page_preview=True)
elif msg['text'] == '/memgraph':
bot.sendChatAction(chat_id, 'typing')
tmperiod = "Last %.2f hours" % ((datetime.now() - graphstart).total_seconds() / 3600)
bot.sendPhoto(chat_id, plotmemgraph(memlist, xaxis, tmperiod))
TOKEN = telegrambot
bot = YourBot(TOKEN)
bot.message_loop()
tr = 0
xx = 0
# Keep the program running.
while 1:
if tr == poll:
tr = 0
timenow = datetime.now()
memck = psutil.virtual_memory()
mempercent = memck.percent
if len(memlist) > 300:
memq = collections.deque(memlist)
memq.append(mempercent)
memq.popleft()
memlist = memq
memlist = list(memlist)
else:
xaxis.append(xx)
xx += 1
memlist.append(mempercent)
memfree = memck.available / 1000000
if mempercent > memorythreshold:
memavail = "可用内存: %.2f GB" % (memck.available / 1000000000)
graphend = datetime.now()
tmperiod = "近 %.2f 小时" % ((graphend - graphstart).total_seconds() / 3600)
for adminid in adminchatid:
bot.sendMessage(adminid, "换个大内存服务器吧\n" + memavail)
bot.sendPhoto(adminid, plotmemgraph(memlist, xaxis, tmperiod))
time.sleep(10) # 10 seconds
tr += 10