跟踪日志的Python脚本

2024-09-30 08:38:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用Python脚本跟踪远程服务器上的日志文件。日志文件滚动速度非常快,我正在使用python sshtail模块跟踪日志文件,并在本地机器上捕获文件中的尾部输出。我能够捕获日志文件并将其保存到本地计算机上的一个文件中,但我的脚本似乎要写两次,并且数据已格式化。 脚本正在工作,但不是我想要的方式,我应该能够运行脚本,在服务器上执行一些操作,跟踪日志,将输出保存到本地计算机上的文件,并使用CTRL-C终止脚本

我写了一些代码,它确实工作,但不是它应该的方式。现在我用的是时间。睡眠等待输出写入本地计算机上的输出文件。你知道吗

#!/usr/bin/python3
import time
import sshtail.tailers as t
import sys
import datetime

username = "username"

logfile = "/var/log/file.log"

k = t.paramiko.RSAKey.from_private_key_file('keyfile')

conn = t.SSHTailer(username,logfile, k, verbose=True)

try:

    conn.connect()
    print(f"Connected to {conn.host}")
    print("Tailing the file..")

except:

    print("Connection unsuccesful...")

conn.tail()


for line in conn.tail():
    print(line)

for line in conn.get_new_lines():
    print(line)

x = conn.remote_file_size

print(f"The file size is: {x}")

time.sleep(10)

output_file = str(conn.host)+"_"+str(datetime.datetime.now().strftime("%Y-%m-%d_%H:%M:%S"))+".txt"

with open(output_file, "a") as f:

    for line in conn.get_new_lines():
        print(line)
        f.write(line)

conn.disconnect()

Tags: 文件inimport服务器脚本fordatetime计算机

热门问题