Это, как я хотел бы сделать это при условии, записи разделяются двоеточием, как они кажутся чтобы быть в вашем примере, он позволяет вам выбрать, какую сторону IP искать, и было бы легко изменить поиск ttl на что-то еще.
Edit: это один будет работать с вашей старой строки, но не новый (используйте нижний сценарий для этого), оставив только это здесь, так что вы потенциально можете попытаться узнать от того, как это работает :)
textfile = "tos 0x0, ttl 62, offset 0, length:40, bad cksum 0 (->4203)!) 150.100.15.6.49153 > 150.100.0.2.57300:"
ttlToSearchFor = 62
ipToSearchFor = "150.100.15"
ipSide = "right"
#Get rid of colon in the length record
lengthRename = textfile.replace("length:", "length ")
#Split by row
individualRow = lengthRename.split(":")
#Loop for each record (assuming they're separated by colons)
for i in range(len(individualRow)):
splitByComma = individualRow[i].split(",")
#Make sure the record is valid
if len(splitByComma) == 5:
#Get the ttl or any other info here
ttl = splitByComma[1].rstrip().lstrip()
#Remove the ttl text and any spaces to leave the number
ttlNumber = ttl.replace("ttl", "").replace(" ", "")
if ttlNumber == str(ttlToSearchFor):
#Get IPs
splitBySpace = individualRow[i].split(" ")
rightIP = splitBySpace[-1]
leftIP = splitBySpace[-3]
#Search the left or right (or both) IPs for a match
if (ipSide == "right" and ipToSearchFor in rightIP) or (ipSide == "left" and ipToSearchFor in leftIP) or (ipSide == "both" and (ipToSearchFor in leftIP or ipToSearchFor in rightIP)):
print individualRow[i]
#You found the record
обновление его, используя Csv материал от должности inspectorg4dget и ваше новую запись, не может проверить его, хотя без этого файла, так что вы, возможно, потребуется, чтобы установить один или два бита
ttlToSearchFor = 62
ipToSearchFor = "150.100.15"
ipSide = "right"
import csv
with open('path/to/input') as textfile:
for row in csv.reader(textfile):
#Make sure the record is the correct format
if len(row) == 10:
#Get the ttl or any other info here
ttl = row[1].rstrip().lstrip()
#Remove the ttl text and any spaces to leave the number
ttlNumber = ttl.replace("ttl", "").replace(" ", "")
if ttlNumber == str(ttlToSearchFor):
#Get IPs
splitBySpace = row[8].split(":")[0].split(" ")
rightIP = splitBySpace[-1]
leftIP = splitBySpace[-3]
#Search the left or right (or both) IPs for a match
if (ipSide == "right" and ipToSearchFor in rightIP) or (ipSide == "left" and ipToSearchFor in leftIP) or (ipSide == "both" and (ipToSearchFor in leftIP or ipToSearchFor in rightIP)):
print row
#You found the record
Каков ваш ожидаемый результат? –
@AvinashRaj Ну, конечная цель - соответствовать правильному TTL с правильным IP. И иметь возможность также анализировать те, которые не соответствуют, когда они должны быть. –