#!/usr/bin/env python

from multiprocessing import *

import sqlite3
import nmap
import time

def scanner (s_arg):
    nm = nmap.PortScanner ()
    nm.scan (hosts=s_arg, arguments="-n -sS -T4 -p 80,81,1080,1081,3128,8080,8081")
    for host in nm.all_hosts ():
        for proto in nm[host].all_protocols ():
            for port in nm[host][proto].keys ():
                if nm[host][proto][port]['state'] == 'open':
                    queue.put ([host, port])

def updater (db):
    while True:
        u_arg = queue.get ()
        if u_arg:
            db.execute ('INSERT INTO open VALUES (?,?,?)', (u_arg[0], u_arg[1], int(time.time())))
        else:
            break

sqlite3.enable_callback_tracebacks (True)
conn = sqlite3.connect ('proxy.db')
db = conn.cursor ()

networks = []
for row in db.execute ('SELECT network FROM cidr WHERE country in (\'CN\')'):
    networks.append (row[0])

queue = Queue ()

updater_p = Process (target = updater, args=(db))
updater_p.daemon = True
updater_p.start ()

pool = Pool (5)
pool.map (scanner, networks)
pool.close ()
pool.join ()

queue.put ([])
updater_p.join ()

conn.commit ()
conn.close ()
