如何腌制包含字符串的文件?

时间:2019-07-13 13:48:32

标签: python pickle

我正在尝试使用以下记录来解析日志文件:

Apr 29 06:56:48 example-server sshd[38254]: pam_unix(sshd:auth): authentication failure; logname= uid=0 euid=0 tty=ssh ruser= rhost=123.183.209.132  user=root
Apr 29 06:56:50 example-server CRON[33299]: pam_unix(cron:session): session closed for user root
Apr 29 06:56:50 example-server sshd[38254]: Failed password for root from 123.183.209.132 port 55181 ssh2
Apr 29 06:56:56 example-server sshd[38254]: message repeated 2 times: [ Failed password for root from 123.183.209.132 port 55181 ssh2]
Apr 29 06:56:59 example-server sshd[38254]: fatal: Read from socket failed: Connection reset by peer [preauth]
Apr 29 06:56:59 example-server sshd[38254]: PAM 2 more authentication failures; logname= uid=0 euid=0 tty=ssh ruser= rhost=123.183.209.132  user=root

我正在尝试使文件腌制

with open('auth.log', 'rb') as logs:
    db = pickle.load(logs)

我收到错误消息:

TypeError: a bytes-like object is required, not 'str'

1 个答案:

答案 0 :(得分:0)

类似您的日志文件不是由pickle模块创建的。

  

pickle模块实现了二进制协议,用于序列化和   反序列化Python对象结构。 “腌制”是过程   从而将Python对象层次结构转换为字节流,并且   “解开”是相反的操作[1]

因此,更好的方法可能是加载日志文件并将其解析为文本。例如,您可以使用以下命令选择所有致命错误:

db = []
with open('auth.log', 'r') as logs:
    for log in logs: #for each line
        if 'fatal' in log:
            db.append(log)

您可以找到有关解析日志文件here的更多信息。