import time
import shodan
import datetime
import sys

SHODAN_API_KEY = ""

api = shodan.Shodan(SHODAN_API_KEY)
netblock_filename = "netblock.txt"


def retrieve_api_results(netblock_filename,query):
    writefile = netblock_filename+'.html'
    f = open(writefile, 'a')
    
    f.write(query+'<br>')
    results = api.search('net:%s' % query)
    #Show the results
    print 'Results found: %s \n' % results['total']
    if results['total'] == 0:
        f.write('Results found: %s \n<br /><br />' % results['total'])
    else:
        f.write('Results found: %s \n<br />' % results['total'])
    
    #print/write results
    for result in results['matches']:
        print 'Timestamp:%s' % result['timestamp']
        f.write('Timestamp:%s <br />' % result['timestamp'])
        
        print 'IP: %s Port: %s' % (result['ip_str'], result['port'])
        f.write('IP: %s Port: %s <br />' % (result['ip_str'], result['port']))
        
        print result['data']
        mytext = "<br />".join(result['data'].split("\n"))
        f.write(mytext)
        f.write('<br />')
        
        print ''
        f.write('<br />')
    #sleep cuz the api sux
    time.sleep(15)

def write_html_report_header(netblock_filename):
    writefile = netblock_filename+'.html'
    now = datetime.datetime.now()
    
    html_string = '''
    <html>
    <head>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
        <style>body{ margin:0 100; background:whitesmoke; }</style>
    </head>
    <body>
        <h1>Shodan Report -- Generated:  ''' +str(now)+ '''</h1>
    '''
    f = open(writefile, 'w')
    f.write(html_string)


    
def write_html_report_footer(netblock_filename):
    writefile = netblock_filename+'.html'
    
    html_string = '''      
        </body>
        </html>
    '''
    f = open(writefile, 'a')
    f.write(html_string)
    
    
#open ths file of netblocks, ips, or domains
try:
	raw_iocs = open(netblock_filename)
except Exception, e:
	sys.exit('%s : File not found' % netblock_filename)

#open our html file to write output
write_html_report_header(netblock_filename)

#loop thru each one, strip at the end for any rogue whitespace
#and skip any comments
for raw_ioc in raw_iocs:
    while True:
        try:
            if not raw_ioc.strip():
                continue
            # skip any comments
            elif raw_ioc.startswith("#"):
                continue
            else:
                print 'netblock:%s' % raw_ioc.strip()
                retrieve_api_results(netblock_filename,raw_ioc.strip())
            break
        except shodan.APIError, e:
            print 'Error: %s for %s, retrying...' % (e, raw_ioc.strip())
            
#write the footer of the html output
write_html_report_footer(netblock_filename)
