使用python正则表达式显示表的输出

迪瓦卡·莎玛

我是python的新手。我必须从telneting一个“被测设备”中获取一张表,并使用python在日志文件中获取它,而我确实使用下面的程序

import os
import sys
import getpass
import re
import telnetlib

HOST = "ip of host"
user = raw_input("Enter your remote account: ")
password = raw_input("Enter the password: ")

tn = telnetlib.Telnet(HOST)

tn.read_until("login: ")
tn.write(user + "\n")
tn.read_until("Password: ")
tn.write(password + "\n")
tn.read_until("*>")
tn.write("command-to-be-executed\n")
tn.write("exit\n")
output = tn.read_all()
f= open("C:/Python27/Scripts/logfile/module_show.txt" , "w+")
f.write(output)
f.close()
tn.close()

现在,我必须读取提取的日志文件,并根据第一列和最后一列打印以下特定行:

| ER | 2 | 252 | wPWs_sTE1-3-2 | | 3.3.3.3 | 30002 | 30002 | sUMoF |

| ER | 1 | 10251 | wPWd_sTE1-3-1 | | 3.3.3.3 | 100000 | 32768 | dUMoF |

我为此编写了一个单独的程序,但这不起作用。请参阅下面的程序:

import re

regex = re.compile("^(\|ER)")
with open("C:/Python27/Scripts/logfile/module_show.txt") as f:
    for line in f:
        result = regex.search(line)
        if result:
            print line

f.close()

请帮我解决同样的问题吗?

迪瓦卡·莎玛

谢谢大家

经过更多的思考后,我发现了这一点,在实施regexp之前,我没有回过头来思考:

import os
import sys
import getpass
import re
import telnetlib

HOST = "ip address"
user = raw_input("Enter your remote account: ")
password = raw_input("Enter the password: ")

tn = telnetlib.Telnet(HOST)

tn.read_until("login: ")
tn.write(user + "\n")
tn.read_until("Password: ")
tn.write(password + "\n")
tn.read_until("*>")
tn.write("command to be executed\n")
tn.write("exit\n")
output = tn.read_all()
f= open("C:/Python27/Scripts/logfile/module_show.txt" , "w+")
f.write(output)
f.close()
tn.close()
regex = re.compile("(F\s\|\r)$")
with open("C:/Python27/Scripts/logfile/module_show.txt") as f:
    for line in f:
        result = regex.search(line)
        if result:
            print line
f.close()

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

使用Python的正则表达式

来自分类Dev

使用Python的正则表达式

来自分类Dev

Python - 在 Findall 之前和之后显示键值(正则表达式,输出)

来自分类Dev

diffstat输出的Python正则表达式

来自分类Dev

正则表达式Python将输出写入文件

来自分类Dev

Python正则表达式未提供所需的输出

来自分类Dev

正则表达式Python将输出写入文件

来自分类Dev

正则表达式中的Python输出

来自分类Dev

使用正则表达式剥离grep的输出

来自分类Dev

使用grep的正则表达式无输出

来自分类Dev

使用正则表达式进行sed替换输出

来自分类Dev

在 cat 输出上使用多行正则表达式

来自分类Dev

无法使用正则表达式获取输出

来自分类Dev

Python正则表达式-(\ w +)与复杂表达式一起使用时会产生不同的输出

来自分类Dev

如何使用python使用正则表达式输出大写

来自分类Dev

如何使用python使用正则表达式输出大写

来自分类Dev

正则表达式输出计数

来自分类Dev

正则表达式在 Python 中未按预期显示

来自分类Dev

使用正则表达式显示目录列表

来自分类Dev

使用正则表达式显示目录列表

来自分类Dev

使用正则表达式解析表-Java

来自分类Dev

使用正则表达式解析HTML表行

来自分类Dev

正则表达式显示错误

来自分类Dev

正则表达式以显示>引号

来自分类Dev

正则表达式显示数组

来自分类Dev

Python:使用 JSON API 链接通过正则表达式显示命名捕获组

来自分类Dev

在python中使用正则表达式断言

来自分类Dev

python:使用正则表达式获取情节

来自分类Dev

Python-在正则表达式中使用变量