import datetime
import paramiko
import time
import os
class ScanError(object):
def __init__(self):
self._ssh = paramiko.SSHClient()
self.last_error_log = None
self._init()
def _init(self):
os.chdir("data") # 打算将报错信息保存到data目录下
self._ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self._ssh.connect("192.168.1.10", username="root", password="XXXXXX")
error_log = self.get_error_log(500)
self.last_error_log = error_log
# 检测最近三天有没有报错信息
today = datetime.date.today()
yesterday = today - datetime.timedelta(days=1)
the_day_before_yesterday = today - datetime.timedelta(days=2)
error_log_str = " ".join(error_log)
if error_log_str.find(str(today)) > -1 or error_log_str.find(str(yesterday)) > -1 or error_log_str.find(str(the_day_before_yesterday)) > -1:
self.save_error_log("error.txt", error_log)
print("内网最近三天有错误信息,请查看")
os.popen("error.txt")
def get_error_log(self, num=200):
cmd = "cd /data/www/sg/sg_dev/socket/log&&tail -n {} sg_error.log".format(num)
stdin, stdout, stderr = self._ssh.exec_command(cmd)
error_log = [i.decode("utf-8") for i in stdout.read().splitlines() if i]
return error_log
@staticmethod
def save_error_log(file_name, log: list):
with open(file_name, "w", encoding="utf-8") as f:
f.write(" ".join(log))
def run_forever(self, interval=30, show_error=True):
"""运行检测工具
:param interval: 检测间隔
:param show_error: 是否检测到报错就自动弹出显示
:return:
"""
while 1:
time.sleep(interval)
error_log = self.get_error_log()
if error_log != self.last_error_log and " ".join(set(error_log) - set(self.last_error_log)).find("ERROR") > -1:
self.last_error_log = error_log
file_name = time.strftime("%Y-%m-%d-%H-%M-%S.txt", time.localtime(time.time()))
print("{} 检测到内网有新的错误信息".format(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))))
self.save_error_log(file_name, error_log)
if show_error:
os.popen(file_name)
if __name__ == "__main__":
ScanError().run_forever()