0

Basically what I am trying to do is check stdout messages as they come in for an ip address. If the have an ip address then the entire line will be added to a list for further action later on. the format of the stdout message looks like the line below, though the ip address varies obviously.

"192.168.1.1 17Dec2020 string more-strings more-strings"

I would like to do something like:

for line in stdout.readlines():
    if line.split()[0] is an ip address:
        list.append(line)

and if the first split doesn't contain an ip address it should be ignored and proceed on to the next line.

I have every thing working I am just trying to add the "if statement" above to reduce some of the lines I have to work with. If possible I would prefer to avoid a regex, but I can certainly go that route if necessary.

  • 1
    you need to use regex. there's no need to split the input you just need to search the input for regex pattern. – El. Nov 25 '20 at 17:52
  • 1
    https://stackoverflow.com/questions/10086572/ip-address-validation-in-python-using-regex – El. Nov 25 '20 at 17:56
  • @El. Thank you I was afraid of that. I have it working with a regex but was hoping there was a better way to do it without having to run every line through the regex. The reason I was doing the split is because if there is an ip in any of the other lines but not at the start then those lines are irrelevant to what I am doing and I only want to work with the lines that have the IP at the start with the script I am working on. – fly1ng_circus Nov 25 '20 at 19:56
  • what's the reason you want to avoid regex? if you compile it first, it's pretty low overhead to check the line. You _could_ check for a bunch of characteristics like finding 3 periods and splitting `line.split()[0]` on periods and checking that you get numbers under 255, etc. but that would not be superior to regex... – Ben Nov 25 '20 at 20:41

1 Answers1

0

For Python3 only:

import ipaddress

a_list = []
for line in stdout.readlines():
    try:
        ipaddress.IPv4Network(line.split()[0])
        a_list.append(line)
    except AddressValueError:
        pass
El.
  • 1,217
  • 1
  • 13
  • 23