编写一个有效的Ubuntu日志监控脚本可以帮助你实时监控系统日志,及时发现和解决问题。以下是一个简单的Python脚本示例,使用tail -f命令来实时监控日志文件,并使用subprocess模块来执行命令。
import subprocess
import time
def monitor_log(log_file):
# 使用tail -f命令实时监控日志文件
command = ["tail", "-f", log_file]
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
try:
while True:
line = process.stdout.readline()
if line:
print(line.strip()) # 打印新的一行日志
time.sleep(0.1) # 稍微休眠一下,避免CPU占用过高
except KeyboardInterrupt:
print("停止监控")
process.terminate()
if __name__ == "__main__":
log_file = "/var/log/syslog" # 你可以根据需要修改日志文件路径
monitor_log(log_file)
导入模块:
subprocess:用于执行外部命令。time:用于控制循环的休眠时间。定义monitor_log函数:
subprocess.Popen执行tail -f命令,实时监控指定的日志文件。stdout=subprocess.PIPE和stderr=subprocess.PIPE将标准输出和标准错误重定向到管道,以便我们可以读取它们。text=True参数确保输出是文本格式,而不是字节格式。循环读取日志:
process.stdout.readline()读取新的一行日志。time.sleep(0.1)稍微休眠一下,避免CPU占用过高。处理中断:
try...except KeyboardInterrupt捕获用户中断(例如按下Ctrl+C),并优雅地终止进程。主程序:
/var/log/syslog)。monitor_log函数开始监控。这个脚本是一个基础示例,可以根据实际需求进行扩展和优化。