首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >根据syslog名称中的日期查找syslog文件

根据syslog名称中的日期查找syslog文件
EN

Stack Overflow用户
提问于 2022-04-12 14:12:30
回答 1查看 77关注 0票数 0

我正在编写一个Python脚本,它将使我能够更好地找到特定的syslog文件。脚本只需输入有关机器的IP地址,然后输入日期( YYYYMMDD格式),因为服务器上每天有一个日志文件。

脚本很大程度上是从一个类似的脚本中复制和改编的,就像我之前的一个同事程序员所做的那样。但是我没有他在Python方面的专业知识,他也没有在他的代码上留下评论。

代码语言:javascript
复制
# This Python file uses the following encoding: utf-8
import os, sys, re
name = raw_input("IP Address? \n")

dir = os.listdir(os.getcwd())

flag_equip = False
flag_h_start = True
flag_h_end = True
flag_date = True
for n in dir :
        if(n!="syslog_hosts" and n!="syslog_hosts.avec.domain" and n!="syslog_hosts.BKP"):
                for nn in os.listdir("/applis/syslog/syslog_cpe"):
                        if(re.search(name,nn)):
                                flag_equip = True
                                print("Equipment found!")
                                while(flag_date):
                                    date = raw_input("date AAAAMMJJ ?\n")
                                    if(re.search("[\d]{8}$",date)):
                                        flag_date = False
                                for nnn in os.listdir("/applis/syslog/syslog_cpe"+"/"+n+"/"+nn):
                                        raw_filename = nnn.split(".")
                                        for i in raw_filename :
                                                if(i==date):
                                                        break
          
         
          
         
if(flag_equip==False):
        print("Equipment not found")

我对我必须输入日期的部分有问题。不管我在日期上写了什么,它总是给我以下的错误。IP地址与我输入的地址匹配,但不匹配始终是第一个机器的日期。

代码语言:javascript
复制
  File "scriptsyslog.py", line 21, in <module>
    for nnn in os.listdir("/applis/syslog/syslog_cpe"+"/"+n+"/"+nn):
OSError: [Errno 2] No such file or directory:'/applis/syslog/syslog_cpe/.bash_history/100.117.130.80.20220404.log'

我的代码看起来可能有点奇怪,但这是因为它还没有完成。我希望这足够清楚。日志文件都是以"IP address.log“格式命名的,例如100.117.130.80.20220410.log

提前谢谢你。这是我在StackOverflow上的第一个问题。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-04-12 18:12:22

下面是修复脚本的尝试。

它不需要交互式I/O,而是将IP地址和日期作为命令行参数读取。我想您会发现,这既更便于用户交互使用,也更容易从其他脚本编程使用。

我猜不出您的文件和目录树是什么样子,但是我已经根据一些猜测重新实现了代码。困难的部分之一是找出如何给变量更少的误导或神秘的名字,但你的问题并没有解释文件是如何组织的,所以我可能猜错了一些部分。

您的原始脚本看起来像是在遍历多个嵌套目录,但是如果您的散文描述是正确的,您只想扫描一个目录并查找指定IP地址和日期的文件。这只是假设您的所有文件都在/applis/syslog/syslog_cpe中,并且对当前目录中的文件的扫描是对先前工作脚本的错误添加。

代码语言:javascript
复制
# Stylistic fix: Each import on a separate line
import os
import sys

if len(sys.argv) != 3:
    print("Syntax: %s <ip> <yyyymmdd>" % sys.argv[0].split('/')[-1])
    sys.exit(1)

filename = os.path.join(
    "/applis/syslog/syslog_cpe",
    sys.argv[1] + "." + sys.argv[2] + ".log")
if os.path.exists(filename):
    print(filename)
else:
    # Signal failure to caller
    sys.exit(2)

你的剧本还有很多其他的问题;这里有一个尝试,我试图把你的剧本搞清楚,我要离开这里,以防它能让你开心或启发你。

代码语言:javascript
复制
# Stylistic fix: Each import on a separate line
import os
import sys
import re


# Stylistic fix: Encapsulate main code into a function
def scanlog(ip_address, date, basedir="/applis/syslog/syslog_cpe"):
    """
    Return any log in the specified directory matching the
    IP address and date pattern.
    """
    # Validate input before starting to loop
    if not re.search(r"^\d{8}$", date):
        raise ValueError("date must be exactly eight digits yyyymmdd")
    if not re.search(r"^\d{1,3}(?:\.\d{1,3}){3}$", ip_address):
        raise ValueError("IP address must be four octets with dots")

    for file in os.listdir(basedir):
        # Stylistic fix: use value not in (x, y, z) over value != x and value != y and value != z
        # ... Except let's also say if value in then continue
        if file in ("syslog_hosts", "syslog_hosts.avec.domain", "syslog_hosts.BKP"):
            continue
        # ... So that we can continue on the same indentation level
        # Don't use a regex for simple substring matching
        if file.startswith(ip_address):
            # print("Equipment found!")
            if file.split(".")[-2] == date:
                return file
    # print("Equipment not found!")


# Stylistic fix: Call main function if invoked as a script
def main():
    if len(sys.argv) != 3:
        print("Syntax: %s <ip> <yyyymmdd>" % sys.argv[0].split('/')[-1])
        sys.exit(1)
    found = scanlog(*sys.argv[1:])
    if found:
        print(found)
    else:
        # Signal error to caller
        sys.exit(2)

if __name__ == "__main__":
    main()

没有理由单独指定编码;Python 3源代码通常默认使用UTF-8,但是这个脚本不包含任何非ASCII的字符,因此它甚至都不重要。

我认为这也适用于Python 2,但它是用Python 3编写和测试的,我不认为继续停留在Python 2上是有意义的。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71844242

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档