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项目发布为exe可执行程序过程分享

1. 手动制作python的exe可执行程序Python没有内建一个编译为exe的功能。给python程序的部署带来不少的麻烦。所以就会出现一些py2exe之类的很不错的工具,用于自动把...

学习python 之编写简单乘法运算题

实现代码: #! /usr/bin/python //处理程序 #filename jiafa.py //文件名 import sys import r...

Django Rest framework解析器和渲染器详解

Django Rest framework解析器和渲染器详解

解析器 解析器的作用就是服务端接收客户端传过来的数据,把数据解析成自己想要的数据类型的过程. 本质就是对请求体中的数据进行解析. Content-type:用于声明我给你传的是什么类型...

Pandas 重塑(stack)和轴向旋转(pivot)的实现

import numpy as np import pandas as pd from pandas import Series,DataFrame 一、重塑 stack:...

Python数据报表之Excel操作模块用法分析

Python数据报表之Excel操作模块用法分析

本文实例讲述了Python数据报表之Excel操作模块用法。分享给大家供大家参考,具体如下: 一 点睛 Excel是当今最流行的电子表格处理软件,支持丰富的计算函数及图表,在系统运营方面...