使用python regex显示表的输出

时间:2016-12-23 06:25:33

标签: python

我对python很新。我不得不从telnett"被测设备"中取出一张桌子。并使用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()

请帮我解决一下吗?

1 个答案:

答案 0 :(得分:0)

谢谢大家,

经过一段时间的思考后,我想出了这一点,在实施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()