#coding:utf8
'''
Created on 2014年8月28日
@author: silence
'''
import socket
import sys
import sqlite3
from multiprocessing import Pool
import time
conn = None
cur = None
#set default encoding as UTF-8
reload(sys)
sys.setdefaultencoding('utf-8')
#----------------------------------------------------------------------
def InitDB():
"""init db and conn,cur"""
global conn,cur
conn = sqlite3.connect(database='ipscan.db')
cur = conn.cursor()
cur.execute('''create table if not exists ValidIPAndPort(host varchar(16) not null,port varchar(5) not null)''')
#print 'table created or prepared.'
#----------------------------------------------------------------------
def getLocalIP():
"""get local ip"""
localIP = socket.gethostbyname(socket.gethostname())
localIP = localIP[:localIP.rfind('.')+1]
return localIP
#----------------------------------------------------------------------
def findValid(target):
"""if the link canbe set up then write it to DB"""
global cur,conn
host = target[0]
port = target[1]
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
try:
s.connect((host,port))
print 'Connect OK ------ %s:%d' %(host,port)
cur.execute('''insert into ValidIPAndPort(host,port) values('%s','%s')''' %(host,port))
conn.commit()
s.close()
except:
pass
#----------------------------------------------------------------------
def closeDB():
"""close conn,cur"""
global conn,cur
cur.close()
conn.close()
print 'closed.'
if __name__ == "__main__":
target = list()#keep the pairs contains of host:ip like 127.0.0.1:80
localIP = getLocalIP()
for ip4 in xrange(1,256):#the C addr where local pc in
host = localIP+str(ip4)
for port in xrange(1,1024):#the port number
target.append((host,port))
InitDB()
print 'start scan~~~'
t1=time.time()
pool = Pool(50)#build in process pool
pool.map(func=findValid, iterable=target)
pool.close()
pool.join()
t2=time.time()
closeDB()
print 'time spend:%f' %(t2-t1)
python 简易ipscanner
最新推荐文章于 2022-11-14 23:45:51 发布