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.

112 lines
4.3 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. # Store response in 'json_data'
  15. json_data = requests.get(main_api + x).json()
  16. # Checks to see if there is a 'message' field in the json data and
  17. # prints the message instead of printing our formatted data.
  18. # This is done because messages are always an error with this api.
  19. if 'message' in json_data:
  20. print('\nThe IP "{}" is {}'.format(x, json_data['message']))
  21. # Print out wanted JSON data formatted nicely
  22. else:
  23. print('\nAS: {}\n'
  24. 'City\State: {}, {}\n'
  25. 'Country: {}\n'
  26. 'ISP: {}\n'
  27. 'IP: {}\n'
  28. 'MX: {}'.format(
  29. json_data['as'],
  30. json_data['city'],
  31. json_data['regionName'],
  32. json_data['country'],
  33. json_data['isp'],
  34. json_data['query'],
  35. x))
  36. # Added exception handling of key errors to help identify problems when
  37. # reading the json data
  38. except KeyError:
  39. traceback.print_exc(file=sys.stdout)
  40. print('Key Error')
  41. print('JSON: ')
  42. print(json_data)
  43. def findMX(host):
  44. """Looks up the MX record of a host"""
  45. p = os.popen('host -t MX ' + host)
  46. # initialize dicts
  47. std_out = []
  48. # Stores the standard output of p(above)
  49. split = []
  50. # Used to hold the a line in std_out that we want to split.
  51. MXServer = []
  52. # The server address that we are sending to the api.
  53. # Append terminal output to list std_out
  54. for line in p:
  55. if re.search('not found', line):
  56. print('No MX record found querying ' + host)
  57. query_api([host])
  58. break
  59. # Check to see if 'domain name pointer' is in the line and finds the
  60. # ip associated with the pointer to do a query on. Created for IPs that
  61. # do not have a easily parsed MX record return.
  62. elif re.search('domain name pointer', line):
  63. print(line)
  64. print('Domain name pointer found querying original host: ' + host)
  65. query_api([host])
  66. extra = re.search('.in-addr.arpa .*', str(line))
  67. # This finds out the 'extra' stuff I dont really care about. i only
  68. # need the IP that is in the line before .in-addr.arpa
  69. thing = line.replace(extra.group(0), '')
  70. # This takes the line and replaces what is stored in the 'extra'
  71. # variable with nothing and gives us the 'thing' we want to query,
  72. # an IP address.
  73. print('\nDomain Name pointer Query: ' + thing)
  74. query_api([thing.rstrip()])
  75. break
  76. std_out.append(line)
  77. p.close
  78. # split line into dict and return MX servers
  79. i = 0
  80. for x in std_out:
  81. # When using os.popen it basically acts like a terminal allowing you to
  82. # run terminal commands from your Python script and use its output. We
  83. # are using as an example 'host -t MX google.com' the output would look
  84. # like:
  85. # google.com mail is handled by 30 alt2.aspmx.l.google.com
  86. # google.com mail is handled by 40 alt3.aspmx.l.google.com
  87. # google.com mail is handled by 10 aspmx.l.google.com
  88. # google.com mail is handled by 20 alt1.aspmx.l.google.com
  89. # google.com mail is handled by 50 alt4.aspmx.l.google.com
  90. split = std_out[i].split()
  91. i = i + 1
  92. # We use .split() method to split the std_out list entry by spaces
  93. MXServer.append(split[-1])
  94. # We take the last item in the split(aspmx.l.google.com) and append it
  95. # to the list 'MXServer'
  96. query_api(MXServer)
  97. # Now we send the list 'MXServer' to the query_api function
  98. if __name__ == "__main__":
  99. parser = argparse.ArgumentParser()
  100. parser.add_argument("host", help="hostname to lookip")
  101. args = parser.parse_args()
  102. findMX(args.host)