Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 正则表达式查找搜索项并将结果放入另一个数据文件?_Python_Regex_Scripting_Python 2.7_Cisco - Fatal编程技术网

Python 正则表达式查找搜索项并将结果放入另一个数据文件?

Python 正则表达式查找搜索项并将结果放入另一个数据文件?,python,regex,scripting,python-2.7,cisco,Python,Regex,Scripting,Python 2.7,Cisco,我不确定这个问题的标题是否正确,所以让我提供一些背景信息。我有两个文本文件。一个名为data.txt,另一个名为results.txt。在数据文件中,我得到了Cisco网络设备上“显示版本”的结果。如下所示: Cisco IOS Software, s72033_rp Software (s72033_rp-ADVIPSERVICESK9_WAN-M), Version 12.2(33)SXI4, RELEASE SOFTWARE (fc3) Technical Support: http://

我不确定这个问题的标题是否正确,所以让我提供一些背景信息。我有两个文本文件。一个名为data.txt,另一个名为results.txt。在数据文件中,我得到了Cisco网络设备上“显示版本”的结果。如下所示:

Cisco IOS Software, s72033_rp Software (s72033_rp-ADVIPSERVICESK9_WAN-M), Version 12.2(33)SXI4, RELEASE SOFTWARE (fc3)
Technical Support: http://www.cisco.com/techsupport
Copyright (c) 1986-2010 by Cisco Systems, Inc.
Compiled Sat 29-May-10 17:54 by prod_rel_team

ROM: System Bootstrap, Version 12.2(17r)SX6, RELEASE SOFTWARE (fc1)

 core-router uptime is 2 years, 5 weeks, 1 day, 5 hours, 47 minutes
Uptime for this control processor is 2 years, 5 weeks, 1 day, 4 hours, 50 minutes
Time since san-qrc1 switched to active is 2 years, 5 weeks, 1 day, 4 hours, 56 minutes
System returned to ROM by reload at 16:12:08 PDT Fri Aug 27 2010 (SP by reload)
System restarted at 16:19:33 PDT Fri Aug 27 2010
System image file is "sup-bootdisk:s72033-advipservicesk9_wan-mz.122-33.SXI4.bin"
Last reload reason: Reload Command



This product contains cryptographic features and is subject to United
States and local country laws governing import, export, transfer and
use. Delivery of Cisco cryptographic products does not imply
third-party authority to import, export, distribute or use encryption.
Importers, exporters, distributors and users are responsible for
compliance with U.S. and local country laws. By using this product you
agree to comply with applicable laws and regulations. If you are unable
to comply with U.S. and local laws, return this product immediately.

A summary of U.S. laws governing Cisco cryptographic products may be found at:
http://www.cisco.com/wwl/export/crypto/tool/stqrg.html

If you require further assistance please contact us by sending email to
export@cisco.com.

cisco WS-C6509-E (R7000) processor (revision 1.5) with 983008K/65536K bytes of memory.
Processor board ID XXXXXXXXXX
SR71000 CPU at 600Mhz, Implementation 0x504, Rev 1.2, 512KB L2 Cache
Last reset from s/w reset
35 Virtual Ethernet interfaces
51 Gigabit Ethernet interfaces
26 Ten Gigabit Ethernet interfaces
1917K bytes of non-volatile configuration memory.
8192K bytes of packet buffer memory.

65536K bytes of Flash internal SIMM (Sector size 512K).
Configuration register is 0x2102
python
Python 2.7.3 (default, Aug  1 2012, 05:16:07) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> with open("data.txt") as infile:
...     text = infile.read()
... 
>>> import re
>>> regex = re.compile(
...     r"""^(?P<device>\S*)           # Match non-whitespace device name
...     \suptime\sis\s                 # Match " uptime is "
...     (?P<uptime>[^\r\n]*)           # Match until end of line --> uptime
...     .*?^System\simage\sfile\sis\s  # Match intervening text
...     "[^:]*:                        # Match from quote to colon
...     (?P<sifilename>[^"]*)          # Match everything until quote --> filename
...     .*?^cisco\s                    # Match intervening text
...     (?P<model>\S*)                 # Match non-whitespace model name
...     .*?^Processor\sboard\sID\s     # Match intervening text
...     (?P<serialno>[^\r\n]*)         # Match until end of line --> serial no""", 
...     re.DOTALL | re.MULTILINE | re.VERBOSE)
>>> match = regex.search(text)
>>> match.groups()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'groups'
简单地说,我想读取data.txt并拉出某些字符串并将它们放入results.txt。CSV格式很好,但我很乐意只提取数据

例如,脚本将提取相关数据,如设备的主机名(在本例中为核心路由器)、系统映像文件名(s72033-adviservicesk9_wan-mz.122-33.SXI4.bin)、正常运行时间(2年5周1天5小时47分钟)、序列号(XXXXXXXX)和型号(WS-C6509-E)。所有这些信息都将以制表符分隔的格式放入results.txt中

将来,可以使用不同的data.txt文件,并将数据附加到results.txt中,为我提供数据点的连续记录。我希望这是有道理的。我已经尝试过搜索我正在寻找的内容,但是我找到的大部分内容要么是在文本文件中查找整行内容,要么是获取单词出现的索引号

最后一件事:根据思科设备的型号,所有项目都会有所不同。它周围的文字通常是相同的,但我要寻找的项目将是不同的。如果您能提供任何帮助,我们将不胜感激。提前谢谢

更新

我使用了您提供的脚本,但仍看到以下内容:

Cisco IOS Software, s72033_rp Software (s72033_rp-ADVIPSERVICESK9_WAN-M), Version 12.2(33)SXI4, RELEASE SOFTWARE (fc3)
Technical Support: http://www.cisco.com/techsupport
Copyright (c) 1986-2010 by Cisco Systems, Inc.
Compiled Sat 29-May-10 17:54 by prod_rel_team

ROM: System Bootstrap, Version 12.2(17r)SX6, RELEASE SOFTWARE (fc1)

 core-router uptime is 2 years, 5 weeks, 1 day, 5 hours, 47 minutes
Uptime for this control processor is 2 years, 5 weeks, 1 day, 4 hours, 50 minutes
Time since san-qrc1 switched to active is 2 years, 5 weeks, 1 day, 4 hours, 56 minutes
System returned to ROM by reload at 16:12:08 PDT Fri Aug 27 2010 (SP by reload)
System restarted at 16:19:33 PDT Fri Aug 27 2010
System image file is "sup-bootdisk:s72033-advipservicesk9_wan-mz.122-33.SXI4.bin"
Last reload reason: Reload Command



This product contains cryptographic features and is subject to United
States and local country laws governing import, export, transfer and
use. Delivery of Cisco cryptographic products does not imply
third-party authority to import, export, distribute or use encryption.
Importers, exporters, distributors and users are responsible for
compliance with U.S. and local country laws. By using this product you
agree to comply with applicable laws and regulations. If you are unable
to comply with U.S. and local laws, return this product immediately.

A summary of U.S. laws governing Cisco cryptographic products may be found at:
http://www.cisco.com/wwl/export/crypto/tool/stqrg.html

If you require further assistance please contact us by sending email to
export@cisco.com.

cisco WS-C6509-E (R7000) processor (revision 1.5) with 983008K/65536K bytes of memory.
Processor board ID XXXXXXXXXX
SR71000 CPU at 600Mhz, Implementation 0x504, Rev 1.2, 512KB L2 Cache
Last reset from s/w reset
35 Virtual Ethernet interfaces
51 Gigabit Ethernet interfaces
26 Ten Gigabit Ethernet interfaces
1917K bytes of non-volatile configuration memory.
8192K bytes of packet buffer memory.

65536K bytes of Flash internal SIMM (Sector size 512K).
Configuration register is 0x2102
python
Python 2.7.3 (default, Aug  1 2012, 05:16:07) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> with open("data.txt") as infile:
...     text = infile.read()
... 
>>> import re
>>> regex = re.compile(
...     r"""^(?P<device>\S*)           # Match non-whitespace device name
...     \suptime\sis\s                 # Match " uptime is "
...     (?P<uptime>[^\r\n]*)           # Match until end of line --> uptime
...     .*?^System\simage\sfile\sis\s  # Match intervening text
...     "[^:]*:                        # Match from quote to colon
...     (?P<sifilename>[^"]*)          # Match everything until quote --> filename
...     .*?^cisco\s                    # Match intervening text
...     (?P<model>\S*)                 # Match non-whitespace model name
...     .*?^Processor\sboard\sID\s     # Match intervening text
...     (?P<serialno>[^\r\n]*)         # Match until end of line --> serial no""", 
...     re.DOTALL | re.MULTILINE | re.VERBOSE)
>>> match = regex.search(text)
>>> match.groups()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'groups'
python
Python 2.7.3(默认值,2012年8月1日,05:16:07)
[GCC 4.6.3]关于linux2
有关详细信息,请键入“帮助”、“版权”、“信用证”或“许可证”。
>>>以open(“data.txt”)作为填充:
...     text=infle.read()
... 
>>>进口稀土
>>>regex=re.compile(
…r“”^(?P\S*)#匹配非空白设备名称
…\suptime\sis\s#匹配“正常运行时间为”
…(?P[^\r\n]*)#匹配到行尾-->正常运行时间
....*?^System\simage\sfile\sis\s#匹配中间文本
…“[^:::*:#从引号到冒号匹配
…(?P[^“]*)#匹配所有内容,直到引用-->文件名
....*?^cisco\s#匹配中间文本
…(?P\S*)#匹配非空白模型名称
....*?^Processor\sboard\sID\s#匹配中间文本
…(?P[^\r\n]*)#匹配到行尾-->序列号“”,
…re.DOTALL | re.MULTILINE | re.VERBOSE)
>>>match=regex.search(文本)
>>>match.groups()
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
AttributeError:“非类型”对象没有属性“组”

问题是主机名缩进了1个空格。当我粘贴它时,缩进消失了。但是,当发出“show version”命令时,将显示1个空格缩进。尝试在上面的服务器上运行代码将破坏脚本。移除空间可以让它工作

您可以将文件读入如下字符串:

with open("data.txt") as infile:
    text = infile.read()
然后可以使用正则表达式提取相关信息:

import re
regex = re.compile(
    r"""^(?P<device>\S*)           # Match non-whitespace device name
    \suptime\sis\s                 # Match " uptime is "
    (?P<uptime>[^\r\n]*)           # Match until end of line --> uptime
    .*?^System\simage\sfile\sis\s  # Match intervening text
    "[^:]*:                        # Match from quote to colon
    (?P<sifilename>[^"]*)          # Match everything until quote --> filename
    .*?^cisco\s                    # Match intervening text
    (?P<model>\S*)                 # Match non-whitespace model name
    .*?^Processor\sboard\sID\s     # Match intervening text
    (?P<serialno>[^\r\n]*)         # Match until end of line --> serial no""", 
    re.DOTALL | re.MULTILINE | re.VERBOSE)
match = regex.search(text)
您可以使用此选项写入csv文件,如下所示:

import csv
with open("results.txt", "a") as outfile:
    outcsv = csv.Writer(outfile)
    outcsv.writerow(match.groups())

您可以将文件读入如下字符串:

with open("data.txt") as infile:
    text = infile.read()
然后可以使用正则表达式提取相关信息:

import re
regex = re.compile(
    r"""^(?P<device>\S*)           # Match non-whitespace device name
    \suptime\sis\s                 # Match " uptime is "
    (?P<uptime>[^\r\n]*)           # Match until end of line --> uptime
    .*?^System\simage\sfile\sis\s  # Match intervening text
    "[^:]*:                        # Match from quote to colon
    (?P<sifilename>[^"]*)          # Match everything until quote --> filename
    .*?^cisco\s                    # Match intervening text
    (?P<model>\S*)                 # Match non-whitespace model name
    .*?^Processor\sboard\sID\s     # Match intervening text
    (?P<serialno>[^\r\n]*)         # Match until end of line --> serial no""", 
    re.DOTALL | re.MULTILINE | re.VERBOSE)
match = regex.search(text)
您可以使用此选项写入csv文件,如下所示:

import csv
with open("results.txt", "a") as outfile:
    outcsv = csv.Writer(outfile)
    outcsv.writerow(match.groups())

为什么要用文本文件而不是SNMP公开此信息?为什么要用文本文件而不是SNMP公开此信息?我非常感谢您的帮助。如果不是太麻烦的话,我很想知道你的正则表达式是如何工作的。我可以复制并粘贴您的工作,但我想知道您的代码是如何工作的,以及为什么它是这样工作的。@kiddsupreme:我已经对正则表达式进行了注释。因此,我用上面的内容创建了一个脚本,但是,当我运行它时,我得到了以下信息:python grabber.py Traceback(最近一次调用):print match.groups()中的文件“grabber.py”,第20行AttributeError:'NoneType'对象没有属性'groups',我将代码粘贴到:@kiddsupreme:此错误表示正则表达式不匹配。你把它用在和你贴在这里的内容完全相同的文件上了吗?如果没有,区别是什么?抱歉耽搁了。是的,输入文件“data.txt”与上面看到的完全相同。我不知道为什么会发生错误。代码的格式应该和我的一样吗@?我非常感谢你的帮助。如果不是太麻烦的话,我很想知道你的正则表达式是如何工作的。我可以复制并粘贴您的工作,但我想知道您的代码是如何工作的,以及为什么它是这样工作的。@kiddsupreme:我已经对正则表达式进行了注释。因此,我用上面的内容创建了一个脚本,但是,当我运行它时,我得到了以下信息:python grabber.py Traceback(最近一次调用):print match.groups()中的文件“grabber.py”,第20行AttributeError:'NoneType'对象没有属性'groups',我将代码粘贴到:@kiddsupreme:此错误表示正则表达式不匹配。你把它用在和你贴在这里的内容完全相同的文件上了吗?如果没有,区别是什么?抱歉耽搁了。是的,输入文件“data.txt”与上面看到的完全相同。我不知道为什么会发生错误。代码的格式是否与我的一样@?