gpt4 book ai didi

Python:For循环仅循环txt文件的第一部分

转载 作者:太空宇宙 更新时间:2023-11-03 18:25:09 25 4
gpt4 key购买 nike

最近我必须为实习编写一个脚本来检查子网是否出现在一堆路由器/交换机配置中。

我制作了一个生成输出的脚本。现在我需要第二个脚本(我无法让它工作到一个),它读取输出,如果子网出现,则将其写入 aanwezig.txt,如果没有写入 nietAanwezig .txt.

很多其他答案帮助我制作了这个脚本,它可以工作,但它只针对前 48 个 IP 执行,并且有超过 2000 个......

checkOutput.py的代码:

def main():

file = open('../iprangesclean.txt', 'rb')
aanwezig = open('../aanwezig.txt', 'w')
nietAanwezig = open('../nietAanwezig.txt', 'w')
output = open('output.txt', 'rb')

for line in file:
originalLine = line
line.rstrip()
line = line.replace(' ', '')
line = line.replace('\n', '')
line = line.replace('\r', '')
one,two,three,four = line.split('.')

# 3Byte IP:
ipaddr = str(one) + "." + str(two) + "." + str(three)

counter = 1
found = 0
for lijn in output:

if re.search("\b{0}\b".format(ipaddr),lijn) and found == 0:
found = 1
else:
found = 2

print counter
counter= counter + 1

if found == 1:
aanwezig.write(originalLine)
print "Written to aanwezig"
elif found == 2:
nietAanwezig.write(originalLine)
print "Written to nietAanwezig"
found = 0

file.close()
aanwezig.close()
nietAanwezig.close()


main()

iprangesclean.txt的格式如下:

10.35.6.0/24
10.132.42.0/24
10.143.26.0/24
10.143.30.0/24
10.143.31.0/24
10.143.32.0/24
10.35.7.0/24
10.143.35.0/24
10.143.44.0/24
10.143.96.0/24
10.142.224.0/24
10.142.185.0/24
10.142.32.0/24
10.142.208.0/24
10.142.70.0/24
and so on...

output.txt 的一部分(我无法为您提供所有内容,因为它包含用户信息):

*name of device*.txt:logging 10.138.200.100
*name of device*.txt:access-list 37 permit 10.138.200.96 0.0.0.31
*name of device*.txt:access-list 38 permit 10.138.200.100
*name of device*.txt:snmp-server host 10.138.200.100 *someword*
*name of device*.txt:logging 10.138.200.100

最佳答案

尝试这个改变:

for lijn in output:
found = 0 # put this here
if re.search("\b{0}\b".format(ipaddr),lijn) and found == 0:
found = 1
else:
found = 2

print counter
counter= counter + 1

"""Indent one level so it us in the for statement"""
if found == 1:
aanwezig.write(originalLine)
print "Written to aanwezig"
elif found == 2:
nietAanwezig.write(originalLine)
print "Written to nietAanwezig"

如果我正确理解了这个问题,这应该会引导您走向正确的方向。 if 语句 当前未在for 语句 中执行。如果这确实解决了您的问题,那么您也不需要 found 变量。你可以有这样的东西:

for counter, lijn in enumerate(output, 1):
if re.search("\b{0}\b".format(ipaddr),lijn):
aanwezig.write(originalLine)
print "Written to aanwezig"
else:
nietAanwezig.write(originalLine)
print "Written to nietAanwezig"

print counter

如果我误解了这个问题,请告诉我。

注意我尚未测试上面的代码,请尝试将它们作为起点。

关于Python:For循环仅循环txt文件的第一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23358523/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com