Python - 从系统日志文件中检索信息
我被要求使用 python 编写一个程序来完成作业。
我收到了一个系统日志文件,我必须找出有关它的信息。
我如何找出登录 root 帐户的尝试次数?
任何建议将不胜感激,因为我对 python 很陌生,完全迷失了!
I have been asked to write a program using python for an assignment.
I have been given a syslog file and I have to find things out about it
How do I find out how many attempts were made to login to the root account?
Any advice would be highly appreciated as I am very new to python and completely lost!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要
/var/log/auth.log
,而不是 syslog。它将包含这样的行:
完成该问题的基本、简单的代码如下:
就像用户 calmh 建议的那样,从长远来看,使用正则表达式进行解析可能会更好,但如果您还不知道它们,学习起来可能并不简单。
You want
/var/log/auth.log
, not syslog.It'll contain lines like like this:
Basic, naive code to accomplish the problem would be as follows:
Like user calmh suggested, it will probably be better long-term to parse with regular expressions, but if you don't know them already, it can be non-trivial to learn.
像这样的东西
something like this
您可能需要读取该文件,解析每一行。当您找到与您感兴趣的内容相匹配的行(例如,根登录失败)时,您将增加一个计数器。
看看如何读取文件以及可能的如何使用正则表达式。
如果您要对“实时”日志文件进行此检查(例如每五分钟一次),则需要跟踪已处理的文件量,以免每次都读取全部内容。这稍微复杂一些,因为您需要记住执行之间的状态(文件大小)。在这种情况下,请查看
shelve
模块。You probably need to read the file, parsing each line. When you find a line that matches what you're interested in (failed root login, for example), you increment a counter.
Take a look at how to read files and possibly how to use regular expressions.
If you are going to do this check against a "live" log file, say every five minutes, you need to keep track of how much of the file you have already processed so you don't read it all every time. This is slightly more complicated, because you need to remember state (file size) between executions. In that case, look at the
shelve
module.