#!/usr/bin/env python
import nmap,os,multiprocessing
from termcolor import colored

def ScanPort(ip,listport):
        print colored('IP: %s ------------------------------------------' % (ip),'yellow')
        for port in listport:
                nm = nmap.PortScanner()
                port = str(port)
                nm.scan(ip,port)
                for host in nm.all_hosts():
                        for proto in nm[host].all_protocols():
                                lport = nm[host][proto].keys()
                                lport.sort()
                                for port in lport:
                                        status = nm[host][proto][port]['state']
                                        if ( status == "open" ):
                                                print colored('Protocol:%s \tport : %s\tstate : %s' % (proto,port,status),'red')
                                        else :
                                                print colored('Protocol:%s  \tport : %s\tstate : %s' % (proto,port, status),'green')


def ReadIp(filename):
        with open(filename) as f:
                ip = f.readlines()
                return ip
def Num():
        if num > 20:num = 20
        return num

def MP(listport):
        result = []
        try:
                count = 0
                num = 20
                pool = multiprocessing.Pool(processes = int(num))
                '''ips.ini存储要扫描的IP，一行一个地址'''
                for ip in ReadIp('ips.ini'):
                        print ip
                        count += 1
                        scanport = ScanPort(ip,listport)
                        result.append(pool.apply_async(scanport))
                pool.close()
                pool.join()
        except Exception,e:
                print e


if __name__ ==  "__main__" :
        ''' ablistport定义一个要扫描的端口'''
        ablistport = [20,21,22,80,3306,59878]
        MP(ablistport)
