#!/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_cursor):
    while True:
        u_arg = queue.get ()
        if u_arg:
            db_cursor.execute ('INSERT INTO open VALUES (?,?,?)', (u_arg[0], u_arg[1], int(time.time())))
            #added a commit here
            db_cursor.connection.commit()
        else:
            break
 
sqlite3.enable_callback_tracebacks (True)
conn = sqlite3.connect ('proxy.db')
#db = conn.cursor () #gone to process creation
 
networks = []
for row in db.execute ('SELECT network FROM cidr WHERE country in (\'CN\')'):
    networks.append (row[0])
 
queue = Queue ()
 
#new cursor for each process
updater_p = Process (target = updater, args=(conn.cursor ()))
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 ()
