iT邦幫忙

1

使用 Python 获取 Linux 系统日志

  • 分享至 

  • xImage

我有一台远程服务器,安装的是 CentOS,我现在想通过 Python 获取该服务器上的日志(messages)文件,并将内容写入到一个 txt 文件中

import paramiko

ip = "192.168.4.5"
username = "root"
password = "P@ssw0rd"
log = open("log.txt", "w")

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(ip, port=22, username=username, password=password, timeout=20)
ssh_stdin, ssh_stdout, ssh_stderr = client.exec_command("cat /var/log/messages | grep -i error")
blog.write(str(ssh_stdout.read()))
log.close()
client.close()

通过该方法我可以将日志内容写入到 log.txt 文件中,但是所有脚本内容却写在了同一行。

b'Aug  5 15:45:18 localhost kernel: RAS: Correctable Errors collector initialized.\nAug  5 15:45:19 localhost kernel: [drm] It appears like vesafb is loaded. Ignore above error if any.\nAug  5 15:45:29 localhost mcelog[929]: mcelog: Cannot write MSR_ERROR_CONTROL to /dev/cpu/0/msr\nAug  5 15:45:29 localhost mcelog[929]: mcelog: Cannot write MSR_ERROR_CONTROL to /dev/cpu/1/msr\nAug  5 15:45:42 localhost journal[1474]: Error looking up permission: GDBus.Error:org.freedesktop.portal.Error.NotFound: No entry for geolocation\nAug  5 15:45:42 localhost org.gnome.Shell.desktop[1474]: Errors from xkbcomp are not fatal to the X server\nAug  5 15:45:43 localhost kernel: [drm:vmw_stdu_crtc_page_flip [vmwgfx]] *ERROR* Page flip error -16.\n'

请问这个日志的开头 b 表示什么,有办法去掉吗?

我看了每行日志后面都有换行符,请问我怎么才能在写入 txt 文件的时候,是逐行写入的,而不是在后面加换行符?

powerc iT邦新手 1 級 ‧ 2020-08-05 17:08:50 檢舉
b''可以用decode解決,有b的原因可以參考
https://stackoverflow.com/questions/6269765/what-does-the-b-character-do-in-front-of-a-string-literal
as900 iT邦研究生 4 級 ‧ 2020-08-05 21:00:28 檢舉
理解了,谢谢
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

1
souda
iT邦好手 1 級 ‧ 2020-08-06 09:40:34

直接用snmp來抓比較快!網路上很多套件都現成的.

0
loke0204
iT邦新手 2 級 ‧ 2020-08-11 15:34:20

google rsyslog

我要發表回答

立即登入回答