免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2099 | 回复: 1
打印 上一主题 下一主题

新手求解答多线程问题 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2014-12-26 15:59 |只看该作者 |倒序浏览
本帖最后由 coolxl2014 于 2014-12-26 16:00 编辑

麻烦大牛帮忙看下这个脚本,用socket.connect分别去连接192.168.2.x这个ip段的15个端口,扫描开放状态。超时是2秒,根据我新手的理解。如果扫描1个ip的15个端口,15个线程,应该2秒内能打印出所以结果。但实际情况是结果一条条往外冒,和单线程一样慢。 求大牛帮小弟指出错误。多谢~
  1. # -*- coding: utf-8 -*-
  2. import threading, socket

  3. def host_list(start,end):
  4.     for i in range(start,end,1):   
  5.         ip = net+str(i)
  6.         for x in PortList:        
  7.             port = x
  8.             tmp = []
  9.             tmp.append(ip)
  10.             tmp.append(port)
  11.             list.append(tmp)
  12.     return list

  13. def scan(list):
  14.     while True:        
  15.         if len(list)>0:
  16.             lock.acquire()
  17.             host = list.pop()
  18.             lock.release()
  19.             ip = host[0]
  20.             port = host[1]
  21.             sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  22.             sock.settimeout(Timeout)
  23.             address = (ip, port)            
  24.             try:
  25.                 sock.connect(address)
  26.                 print ip,port,'True'
  27.             except:
  28.                 sock.close()
  29.                 print ip,port,'False'
  30.             sock.close()
  31.         else:
  32.             break

  33. def threads(x):
  34.     thread_tmp=[]
  35.     for i in range(x):
  36.         new_thread=threading.Thread(target=scan(host), args=(i),name='thread'+str(i))
  37.         thread_tmp.append(new_thread)
  38.     for i in thread_tmp:
  39.         i.start()
  40.         i.join()


  41. if __name__ == '__main__':
  42.     net = '192.168.2.'
  43.     Timeout = 2.0
  44.     PortList = [21, 22, 23, 25, 80, 135, 137, 139, 445, 1433, 1502, 3306, 3389, 8080, 9015]
  45.     list = []
  46.     true_list = []
  47.     false_list = []
  48.     lock = threading.Lock()
  49.     host = host_list(1,2)
  50.     threads(15)
复制代码

论坛徽章:
0
2 [报告]
发表于 2014-12-26 19:53 |只看该作者
没仔细看,感觉这里这么写吧
  1. for i in thread_tmp:
  2.     i.start()
  3. for i in thread_tmp:   
  4.     i.join()
复制代码
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP