Python 在Windows上监控Linux日志
import paramiko
import time
def monitor_linux_log(linux_ip, username, password, log_file):
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(linux_ip, username=username, password=password)
while True:
stdin, stdout, stderr = client.exec_command(f"tail -f {log_file}")
for line in stdout:
print(line.strip())
time.sleep(1) # 等待1秒再次读取日志文件
# 调用函数开始监控日志文件
monitor_linux_log('192.168.10.x', '0', '0', '/var/log/messages')
因为tail -f命令执行之后,会一直停在那儿等待新的日志。当知道具体日志,可以匹配日志,然后停止ssh通道,停止脚本运行,Demo如下
from concurrent.futures import ThreadPoolExecutor
import re
import paramiko
import time
linux_ip = ''
username = ''
password = ''
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(linux_ip, username=username, password=password)
flag2 = False
def monitor_linux_log():
stdin, stdout, stderr = client.exec_command(f"tail -f /var/log/messages")
while True:
for line in stdout:
print(line.strip())
if re.search('Destroying ProtocolHandler \[\"http-nio-[0-9]{3,5}\"\]', line.strip()):
global flag2
flag2 = True
print(f"11{flag2}")
client.close()
break
break
def kill_ssh_client():
print(2)
n = 0
while True:
if not flag2 and n < 30:
print(f"22{flag2}")
time.sleep(1)
n += 1
elif flag2 or n >= 30:
print(f"33{flag2}")
client.close()
break
def run():
with ThreadPoolExecutor() as executor:
# 提交任务到线程池,并获取Future对象
future1 = executor.submit(monitor_linux_log)
future2 = executor.submit(kill_ssh_client)
if __name__ == '__main__':
# 调用函数开始监控日志文件
run()
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)