首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >保存文本文件的一部分

保存文本文件的一部分
EN

Stack Overflow用户
提问于 2015-06-08 13:20:45
回答 1查看 162关注 0票数 1

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

这就是我所做的:

代码语言:javascript
复制
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 V2模式:禁用!VTP: VTP陷阱生成:禁用!VTP: MD5摘要: 0x05 0xBB 0x45 0x03 0x57 0xBE 0xBA0x57 !VTP: VTP版本运行:1!调试:调试级别设置为小(1)!调试:新会话日志级别的默认值:3!核:模块实例进程-名称PID日期(年-月-日时间)!核心:

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-06-08 16:44:21

版本和配置寄存器的排序在这里很重要。因此,您最好只迭代文件两次。这样,您就可以将您需要作为组查找的文件的各个部分进行拆分。一次查找版本的值,一次查找配置寄存器。

代码语言:javascript
复制
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

然后再循环一次,只搜索配置版本和"end“。这不是最注重性能的,但由于您没有处理整个文件,希望这将满足您的需要。

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

https://stackoverflow.com/questions/30710263

复制
相关文章

相似问题

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