python多线程扫描端口示例

yipeiwu_com5年前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中字典根据多项规则排序的方法

我们做登录的时候经常会使用到,验证手机号是否正确、向手机发送验证码倒计时60s的问题,我们改如何解决呢?让我们一起来探讨一下吧。如下图: 首先,我们先说说判断手机号码是否正确的问题吧...

django与vue的完美结合_实现前后端的分离开发之后在整合的方法

django与vue的完美结合_实现前后端的分离开发之后在整合的方法

最近接到一个任务,就是用django后端,前段用vue,做一个普通的简单系统,我就是一搞后端的,听到vue也是比较震惊,之前压根没接触过vue. 看了vue的一些文档,还有一些项目,先说...

从头学Python之编写可执行的.py文件

Python可是真强大。但他具体是怎么强大的,让我们一点一点来了解吧(小编每天晚上下班回家会抽时间看看教程,多充实下自己也是好的)。 废话不多说,就讲一下这个背景吧: 事情是这个样子的~...

python 按照固定长度分割字符串的方法小结

有如下的一堆mac地址,需要更改成一定格式,如mac='902B345FB021'改为mac='90-2B-34-5F-B0-21'。 借助python脚本,可以轻松实现,原理就是:字符...

Python对象属性自动更新操作示例

Python对象属性自动更新操作示例

本文实例讲述了Python对象属性自动更新操作。分享给大家供大家参考,具体如下: 在软件设计中会遇到这样的问题:有些属性之间有相互关联。这样,其中的一个属性变化的时候其他的属性也应该跟随...