Last active
September 23, 2015 04:17
-
-
Save jbweber/dbe1c0cba2accada08f7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
import socket | |
# >>> for x in [x for x in dir(socket) if x.startswith('EAI')]: | |
# ... print x, getattr(socket,x) | |
EAI_MAPPING = { | |
'EAI_ADDRFAMILY': -9, | |
'EAI_AGAIN': -3, | |
'EAI_BADFLAGS': -1, | |
'EAI_FAIL': -4, | |
'EAI_FAMILY': -6, | |
'EAI_MEMORY': -10, | |
'EAI_NODATA': -5, | |
'EAI_NONAME': -2, | |
'EAI_OVERFLOW': -12, | |
'EAI_SERVICE': -8, | |
'EAI_SOCKTYPE': -7, | |
'EAI_SYSTEM': -11, | |
} | |
DOCUMENTATION = ''' | |
--- | |
module: zg_nslookup | |
short_description: perform basic hostname -> ip and ip -> hostname lookups | |
description: | |
- performs hostname -> and ip -> hostname lookups by utilizing the python | |
socket.getaddrinfo and socket.gethostinfo methods | |
- currently this module will only lookup ipv4 addresses | |
version_added: "1.9" | |
options: | |
lookup: | |
required: True | |
description: | |
- The hostname or ip address to lookup | |
''' | |
def execute(f, module, input, expected): | |
r = f(input) | |
actual = r[0] | |
expected = expected | |
is_valid = actual == expected | |
module.exit_json(changed=False, | |
actual=list(actual), | |
expected=list(expected), | |
error_code=r[1], | |
is_valid=is_valid) | |
def forward_lookup(hostname): | |
try: | |
r = socket.getaddrinfo(hostname, None, socket.AF_INET) | |
s = {v[4][0] for v in r} | |
return s, None | |
except socket.gaierror as e: | |
return {}, e[0] | |
def reverse_lookup(ip_address): | |
try: | |
print ip_address | |
r = socket.getnameinfo((ip_address, 0), 0) | |
return {r[0]}, None | |
except socket.gaierror as e: | |
return {}, e[0] | |
def valid_ip(input): | |
try: | |
socket.inet_aton(input) | |
return True | |
except: | |
return False | |
def main(): | |
module = AnsibleModule( | |
argument_spec=dict( | |
lookup=dict(required=True), | |
expected=dict(required=True, type='list'), | |
), | |
supports_check_mode=False, | |
) | |
try: | |
lookup = module.params['lookup'] | |
expected = set(module.params['expected']) | |
is_ip = valid_ip(lookup) | |
if not is_ip: | |
execute(forward_lookup, module, lookup, expected) | |
else: | |
execute(reverse_lookup, module, lookup, expected) | |
except Exception as e: | |
module.fail_json(msg='%s' % e) | |
from ansible.module_utils.basic import * | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment