使用Python脚本尾写日志文件

时间:2019-08-14 21:25:06

标签: python python-3.x

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

我确实写了一些代码,它确实起作用了,但不是应该的。现在,我正在使用time.sleep等待输出被写入本地计算机上的输出文件。

#!/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()

1 个答案:

答案 0 :(得分:0)

我建议将time.sleep替换为asyncio.sleep

相关问题