python 简易ipscanner

#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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值