Advertisement
Guest User

Untitled

a guest
Oct 29th, 2017
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.50 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3. import requests
  4. import time
  5. import pymysql
  6. import sys
  7. import logging
  8. import pandas as pd
  9. import urllib3
  10. import socket
  11. import requests
  12. from urllib.parse import urlparse
  13.  
  14. urllib3.disable_warnings()
  15. API = 'https://api.ssllabs.com/api/v2/'
  16.  
  17.  
  18. def check_version(url):
  19.     response = requests.get(url, timeout=10, verify=False)
  20.     http2 = response.headers.get("upgrade")
  21.  
  22.     if http2 == None:
  23.         if response.raw.version == 10:
  24.             return "1.0"
  25.         else:
  26.             return "1.1"
  27.     else:
  28.         return "2"
  29.  
  30.  
  31. def check_http(results, host):
  32.     try:
  33.         endpoints = results["endpoints"]
  34.         df_endpoints = pd.DataFrame(endpoints)
  35.         protocols = df_endpoints.details[0]['npnProtocols']
  36.  
  37.         if "h2" in protocols:
  38.             return "2"
  39.         elif 'h2c' in protocols:
  40.             return "2"
  41.         elif "1.1" in protocols:
  42.             return "1.1"
  43.         else:
  44.             return "1.0"
  45.     except Exception as exc:
  46.         return check_version(host)
  47.  
  48.  
  49. def requestAPI(path, payload={}):
  50.     '''
  51.        This is a helper method that takes the path to the relevant
  52.        API call and the user-defined payload and requests the
  53.        data/server test from Qualys SSL Labs.
  54.        Returns JSON formatted data
  55.    '''
  56.  
  57.     url = API + path
  58.  
  59.     try:
  60.         response = requests.get(url, params=payload)
  61.     except requests.exception.RequestException:
  62.         logging.exception('Request failed.')
  63.         sys.exit(1)
  64.  
  65.     data = response.json()
  66.     return data
  67.  
  68.  
  69. def resultsFromCache(host, publish='off', startNew='off', fromCache='on', all='done'):
  70.     path = 'analyze'
  71.     payload = {
  72.         'host': host,
  73.         'publish': publish,
  74.         'startNew': startNew,
  75.         'fromCache': fromCache,
  76.         'all': all
  77.     }
  78.     data = requestAPI(path, payload)
  79.     return data
  80.  
  81.  
  82. def newScan(host, publish='off', startNew='on', all='done', ignoreMismatch='on'):
  83.     path = 'analyze'
  84.     payload = {
  85.         'host': host,
  86.         'publish': publish,
  87.         'startNew': startNew,
  88.         'all': all,
  89.         'ignoreMismatch': ignoreMismatch
  90.     }
  91.  
  92.     results = requestAPI(path, payload)
  93.     payload.pop('startNew')
  94.     try:
  95.         while results['status'] != 'READY' and results['status'] != 'ERROR':
  96.             time.sleep(30)
  97.             results = requestAPI(path, payload)
  98.         return results
  99.     except Exception as exception:
  100.         return None
  101.  
  102.  
  103. def response_time(url):
  104.     import requests
  105.     return requests.get(url).elapsed.total_seconds()
  106.  
  107.  
  108. def check_ipv6(url):
  109.     # Create variable to store ipv4 and ipv6 array
  110.     ip = []
  111.  
  112.     # parse URL to only get network location address
  113.     parsed_url = urlparse(url).netloc
  114.  
  115.     # Get host by name using socket lib
  116.     response = socket.gethostbyname(parsed_url)
  117.     ip.append(response)
  118.  
  119.     try:
  120.         # Try to get the ipv6 info
  121.         ipv6_info = socket.getaddrinfo(parsed_url, None, family=socket.AF_INET6)
  122.  
  123.         # Get the address from the 3D array returned by getaddrinfo
  124.         ip.append(ipv6_info[-1][-1][0])
  125.  
  126.     except Exception as exception:
  127.         ip.append("none")
  128.  
  129.     return ip
  130.  
  131.  
  132. def check_uptime(url):
  133.     try:
  134.         # Use requests library to get headers of request
  135.         response = requests.get(url)
  136.  
  137.         # and then check the response...
  138.         if response.status_code == 200:
  139.             return True
  140.         else:
  141.             return False
  142.  
  143.     except requests.RequestException as exception:
  144.         return 0
  145.  
  146.  
  147. def check_site(url):
  148.     results = newScan(url)
  149.     if results is None:
  150.         return None
  151.     http = check_http(results, url)
  152.     up = check_uptime(url)
  153.     response = response_time(url)
  154.     ips = check_ipv6(url)
  155.  
  156.     ''' Connect to the database '''
  157.     connection = pymysql.connect(host='localhost',
  158.                                  user='root',
  159.                                  password='Azerty123',
  160.                                  db='websites',
  161.                                  charset='utf8mb4',
  162.                                  cursorclass=pymysql.cursors.DictCursor)
  163.     try:
  164.         with connection.cursor() as cursor:
  165.             sql = "INSERT INTO statistics (url, http_version, response_time, ipv4, ipv6, up) VALUES (%s,%s,%s,%s,%s,%s)"
  166.             cursor.execute(sql, (url, http, response, ips[0], ips[1], up))
  167.             connection.commit()
  168.     finally:
  169.         connection.close()
  170.  
  171.  
  172. file = "websites.csv"
  173. websites = pd.read_csv(file)
  174. for site in websites:
  175.     print(site)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement