保存文本文件的一部分

时间:2015-06-08 13:20:45

标签: python python-3.x text-files

我使用Rancid服务器来保存网络上有关Cisco交换机的信息。我想编写一个Python 3脚本来将数据的配置部分提取到文本文件中。我已经得到了这个工作,但我有一个文件,其中有两次配置,我只想要第一个配置。

这就是我所做的:

import sys

flag = False

start = ('version', 'config-register')
end = ('@\n', 'monitor 6\n', 'end\n')

with open(sys.arbv[1], "r") as file:
         for line in file:

                   if line.startswith(start):
                           file = True;

                   if flag:
                           sys.stdout.write(line)

                   if line.endswith(end):
                           flag = False

具有两次配置的文件使用'version'作为开头,'@\n'作为结束。我试过使用break,但我仍然得到了两个配置。

文件示例:     !VTP:VTP域名:     !VTP:VTP修剪模式:禁用(操作禁用)     !VTP:VTP V2模式:禁用     !VTP:VTP陷阱生成:已禁用     !VTP:MD5摘要:0x05 0xBB 0x45 0x03 0x57 0xBE 0xBA 0x57     !VTP:运行VTP版本:1     !     !DEBUG:调试级别设置为Minor(1)     !DEBUG:新会话日志级别的默认值:3     !     !CORES:模块实例进程名称PID日期(年 - 月 - 日时间)     !CORES:------ -------- --------------- -------- ---------- ---------------     !     !PROC_LOGS:进程PID正常退出堆栈核心日志创建时间     !PROC_LOGS:--------------- ------ ----------- ----- ----- ----- ----------     !

version 5.2(1)N1(4)
logging level feature-mgr 0
hostname 

no feature telnet
feature tacacs+
cfs eth distribute
feature udld
feature interface-vlan
feature lacp
feature vpc
feature lldp
feature vtp
feature fex

username (removed)

**** content removed ****

Interface Section


clock timezone CTD -6 0
line console
  exec-timeout 5
line vty
  session-limit 5
  session-limit 5
  exec-timeout 5
  access-class 3 in
boot kickstart 
boot system 
ip route 
no ip source-route


@


1.75
log
@updates
@
text

1 个答案:

答案 0 :(得分:0)

版本和配置寄存器的顺序在这里很重要。所以你可能最好只重复两次文件。这样,您可以将需要查找的文件部分拆分为组。一旦找到版本的值,一次找到config-register。

import sys

flag = False

VERSION_NAME = r'version'

CONFIG_NAME = r'config-register'

end = ('@\n', 'monitor 6\n', 'end\n')

FILE_NAME = sys.argv[1]


# find the config-register
with open(FILE_NAME, "r") as file:
    start = CONFIG_NAME
    config_found = False

    for line in file:
        if line.startswith(start) and not config_found:
            flag = True                   # correction

        if flag:
            sys.stdout.write(line)
        if flag and line.endswith(end):
            print("Found Break")
            break                          # correction

        if line.startswith(start):
            config_found = True


# find the version
with open(FILE_NAME, "r") as file:
    start = VERSION_NAME
    config_found = False

    for line in file:
        if line.startswith(start) and not config_found:
            flag = True

        if flag:
            sys.stdout.write(line)

        if flag and line.endswith(end):
            print("Found Break")
            break

        if line.startswith(start):
            config_found = True

然后你会再次循环,只搜索配置版本和“结束”。这不是最注重性能的,但由于您没有处理整个文件,希望这可以满足您的需求。