0

I have created a calling in restapi to print results in one array, but i need to compare this data before saving this result, example:

for id in ids:
    try:
        now = datetime.datetime.now()
        token, tokenExpireDate = checkTokenExpireDate(apiUrl, client_id, client_secret, token, now, tokenExpireDate) 
        data = getHostDetails(apiUrl, token, id)['resources'][0]
        local_ip = data['local_ip']
        allowed_range_ip = ['10.20.*', '10.10.*', '172.12.*']
        if local_ip in allowed_range_ip:
            print(local_ip)
        else:
            print(local_ip)
    except Exception as e:
        print({'exception': e, 'id': id})

I want to compare allowed_range_ip with local_ip, if local_ip is true in allowed_range_ip save in array, how i could do this? I'm new using python, so take easy :)

EDIT: Example output script (some random ip's), I want to print only ip's similar to allowed_range_ip:

    10.160.20.02
    172.17.0.9
    10.255.250.68
    10.80.10.20
2
  • Okay, so what happened when you tried the code that you wrote? How is that different from what is supposed to happen? When you say "compare", what exactly does that mean, and how is it different from what your code does? Can you give some examples of what you expect the local_ip values to look like, and explain which should or should not pass the check? It seems like you want to use "wildcards" somehow - am I guessing correctly? Please be explicit. Commented Jun 23, 2021 at 0:49
  • @KarlKnechtel I'm editing this post to append script output, answering your question yes, I'm using wildcards to pass a check on local_ip Commented Jun 23, 2021 at 1:20

1 Answer 1

5

Python's builtin ipaddress module makes this easy. You create an ip_network object, and then you can see if the given ip_address is in that network. For instance:

from ipaddress import ip_address, ip_network

allowed_range_ip = [
    ip_network("10.20.0.0/16"),
    ip_network("10.10.0.0/16"),
    ip_network("172.12.0.0/16"),
]

local_ip1 = ip_address('10.20.30.40')
print(any(local_ip1 in net for net in allowed_range_ip))

local_ip2 = ip_address('10.21.30.40')
print(any(local_ip2 in net for net in allowed_range_ip))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.