我需要从.txt文件中选择IP地址并创建这些地址的列表。
我已经编写了代码,但没有得到预期的结果。已经过了与之相关的StackOverflow发布的答案。
import sys
import re
def get_up_ip():
ip = []
fp = open('./output1.txt', 'r')
for line in fp:
if re.match(r'(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})', line.splitlines()[2]):
ip.append(line.split()[2])
return ip
get_up_ip()
output1.txt :
sw3# show end
----------------------------------------------------------------
Node 10 (fs-az4-10)
----------------------------------------------------------------
Legend:
s - arp O - peer-attached a - local-aged S - static
V - vpc-attached p - peer-aged M - span L - local
B - bounce H - vtep
+-----------------------------------+---------------+-----------------+--------------+-------------+
VLAN/ Encap MAC Address MAC Info/ Interface
Domain VLAN IP Address IP Info
+-----------------------------------+---------------+-----------------+--------------+-------------+
sw:swSer 143.252.78.9 tunnel165
sw:swSer 171.252.232.229 a tunnel1
sw:swSer 17.252.232.77 p tunnel1
sw:swSer 9.252.193.109 a tunnel3
apic#
所需结果:
ip = ['143.252.78.9','171.252.232.229','17.252.232.77','9.252.193.109']
答案 0 :(得分:0)
您的正则表达式为我工作,只需要将line.split()[2]调整为line.split [1]
import sys
import re
def get_up_ip():
ip = []
fp = open('output1.txt', 'r')
for line in fp:
if len(line.split()) > 1:
if re.match(r'(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})', line.split()[1]):
ip.append(line.split()[1])
return ip
print 'Result:'
print get_up_ip()
答案 1 :(得分:-1)
尝试此代码! 一切正常。
import sys
import re
def get_up_ip():
ip = []
fp = open('output.txt', 'r')
f = fp.read()
obj = re.findall(r'(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})[ ]', f)
return obj
print get_up_ip()
输出:
['143.252.78.9', '171.252.232.229', '17.252.232.77', '9.252.193.109']