You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

83 lines
2.6 KiB

  1. import argparse
  2. import requests
  3. import os
  4. import re
  5. import sys
  6. import traceback
  7. def query_api(host):
  8. """Queries the ip-api site in order to check geolocation and mx record of
  9. the host"""
  10. main_api = 'http://ip-api.com/json/'
  11. # For every host do an API request
  12. try:
  13. for x in host:
  14. json_data = requests.get(main_api + x).json()
  15. # Checks to see if there is a 'message' field in the json data and
  16. # prints the message instead of doing a query
  17. if 'message' in json_data:
  18. print('\nThe IP "{}" is {}'.format(x, json_data['message']))
  19. # Print out wanted JSON data formatted nicely
  20. else:
  21. print('\nCity\State: {}, {}\n'
  22. 'Country: {}\n'
  23. 'ISP: {}\n'
  24. 'IP: {}\n'
  25. 'MX: {}'.format(
  26. json_data['city'],
  27. json_data['regionName'],
  28. json_data['country'],
  29. json_data['isp'],
  30. json_data['query'],
  31. x))
  32. # Added exception handling of key errors to help identify problems when
  33. # reading the json data
  34. except KeyError:
  35. traceback.print_exc(file=sys.stdout)
  36. print('Key Error')
  37. print('JSON: ')
  38. print(json_data)
  39. def findMX(host):
  40. """Looks up the MX record of a host"""
  41. p = os.popen('host -t MX ' + host)
  42. # initialize dicts
  43. std_out = []
  44. split = []
  45. MXServer = []
  46. # append terminal output to variable std_out
  47. for line in p:
  48. if re.search('not found', line):
  49. query_api([host])
  50. break
  51. # Checs to see if 'domain name pointer' is in the line and finds the ip
  52. # associated with the pointer to do a query on. Created for IPs that do
  53. # not have a easily parsed MX record return.
  54. elif re.search('domain name pointer', line):
  55. query_api([host])
  56. extra = re.search('.in-addr.arpa .*', str(line))
  57. thing = line.replace(extra.group(0), '')
  58. query_api([thing.rstrip()])
  59. break
  60. std_out.append(line)
  61. p.close
  62. # create iterator
  63. i = 0
  64. # split line into dict and return MX servers
  65. for x in std_out:
  66. split = std_out[i].split()
  67. MXServer.append(split[-1])
  68. i = i + 1
  69. query_api(MXServer)
  70. if __name__ == "__main__":
  71. parser = argparse.ArgumentParser()
  72. parser.add_argument("host", help="hostname to lookip")
  73. args = parser.parse_args()
  74. findMX(args.host)