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
'''

相关文章

Tornado高并发处理方法实例代码

本文主要分享的是一则关于Tornado高并发处理方法的实例,具体如下: #!/bin/env python # -*- coding:utf-8 -*- import tornado...

Python中shutil模块的常用文件操作函数用法示例

os模块提供了对目录或者文件的新建/删除/查看文件属性,还提供了对文件以及目录的路径操作。比如说:绝对路径,父目录……  但是,os文件的操作还应该包含移动 复制 ...

python获取当前文件路径以及父文件路径的方法

python获取当前文件路径以及父文件路径的方法

#当前文件的路径 pwd = os.getcwd() #当前文件的父路径 father_path=os.path.abspath(os.path.dirname(pwd)+os.p...

Python正则表达式和元字符详解

正则表达式 正则表达式是一种强大的字符串操作工具。它是一种领域特定语言 (DSL),不管是 Python 还是在大多数现代编程语言中都是作为库存在。 它们主要面向两种任务: - 验...

django框架使用方法详解

django框架使用方法详解

我的文章的意义 服务端开发,python,django这些内容上面的链接中有详细的阐述. 我写的内容肯定没有上面的完备,准确. 我的文章的价值在于从一个iOS程序员的角度来理解服务端开...