python多线程扫描端口示例

yipeiwu_com6年前Python基础

复制代码 代码如下:

# -*- coding: cp936 -*-
import socket
from threading import Thread,activeCount,Lock
from time import ctime
mutex = Lock()

class Loop(Thread):
    def __init__(self,ip,port,que):
        Thread.__init__(self)
        self.ip     = ip
        self.port   = port
        self.que    = que

    def run(self):
        global mutex
        try:
            client = socket.socket()
            indicator = client.connect_ex((self.ip,self.port))
            if mutex.acquire(1):
                if indicator == 0:
                    que.append(self.ip+'\t'+str(self.port))
                else:
                    print self.ip,'\t',str(self.port),'不可达'
                mutex.release()
        except:
            if mutex.acquire(1):
                print self.ip,'\t',str(self.port),'不可达'
                mutex.release()

class Main(Thread):
    def __init__(self,ip,que):
        Thread.__init__(self)
        self.ip  = ip
        self.que = que

    def run(self):
        i = 0
        while i < 65536:
            if activeCount() <= 200:
                Loop(ip=self.ip,port=i,que=self.que).start()
                i = i + 1

if __name__ == '__main__':
    que = []
    ip = raw_input('IP=')

    main = Main(ip = ip,que = que)
    main.start()

    while True:
        if activeCount() <= 1 and main.isAlive() == False:
            break

    print ''
    f = open('portOpen.py','a')
    f.write("'''")
    f.write(ctime()+'\n')
    f.flush()
    for i in range(0,len(que)):
        print que[i]
        f.write('\t'+que[i]+'\n')
        f.flush()
    f.write("'''")
    f.close()

    raw_input()

'''Mon Jan 13 07:12:53 2014
 localhost 135
 localhost 1028
 localhost 8048
 localhost 8080
 localhost 8181
 localhost 8730
 localhost 12040
 localhost 12897
 localhost 18040
 localhost 18611
''''''Tue Jan 14 10:04:58 2014
 localhost 135
 localhost 1028
 localhost 8048
 localhost 8080
 localhost 8181
 localhost 12897
 localhost 18040
 localhost 18611
'''

相关文章

Python第三方Window模块文件的几种安装方法

Python第三方Window模块文件的几种安装方法

python安装第三方模块 使用软件管理工具pip python自带了包管理工具,就像手机app商城,91助手等软件的功能一样。 python2与python3安装模块的方法相似,值得注...

Python continue继续循环用法总结

Python之 continue继续循环 在循环过程中,可以用break退出当前循环,还可以用continue跳过后续循环代码,继续下一次循环。 假设我们已经写好了利用for循环计算平均...

Python 3.8新特征之asyncio REPL

前言 我最近都在写一些Python 3.8的新功能介绍的文章,在自己的项目中也在提前体验新的Python版本。为什么我对这个Python 3.8这么有兴趣呢?主要是因为在Python 2...

Python基于pygame模块播放MP3的方法示例

本文实例讲述了Python基于pygame模块播放MP3的方法。分享给大家供大家参考,具体如下: 安装pygame(可参考:安装Python和pygame及相应的环境变量配置) pip安...

django drf框架自带的路由及最简化的视图

django-drf框架自带的路由以及最简化的视图,具体内容如下所示: 路由 一.导入模块 from rest_framework.routers import SimpleRout...