'''
Author: aDoN90
'''
import sys
import json
import requests
import pprint
import argparse
import re


API_URL = "https://www.censys.io/api/v1"

UID = "uid"
SECRET = "secret"

proxies = {'http': 'http://127.0.0.1:8080', 'https': 'http://127.0.0.1:8080'}

def querySearch(q,p=1):
	
	params = {
				  "query":q,
				  "page":1,
				  "fields":["parsed.subject_dn"],
				  "flatten": True
				}
	res = requests.post(API_URL + "/search/certificates",json = params, auth=(UID, SECRET))
	

	if res.status_code != 200:
			print "error occurred: %s" % res.json()["error"]
			sys.exit(1)

	count = res.json()["metadata"]["count"]


	for i in range(1,count):
		params = {
				  "query":q,
				  "page":i,
				  "fields":["parsed.subject_dn"],
				  "flatten": True
				}
		res = requests.post(API_URL + "/search/certificates",json = params, auth=(UID, SECRET))
		count = res.json()["metadata"]["count"]
		if res.status_code != 200:
			print "error occurred: %s" % res.json()["error"]
			sys.exit(1)

		for i,j in enumerate(res.json()["results"]):

			#print res.json()["results"][i]['parsed.subject_dn']
			print re.search('CN=(.*)',res.json()["results"][i]['parsed.subject_dn']).groups(0)[0]
		
	
parser = argparse.ArgumentParser(description="Author: aDoN90",epilog="Censys Search example: python censysadon.py -q <Organization Name>")
parser.add_argument("-q", required=True, metavar="query", help="Query Search")

if len(sys.argv)==1:
    parser.print_help()
    sys.exit(1)
args = parser.parse_args()
print "surprise motherfucker"
querySearch(args.q)
