分享

python 批量ping一个网段 返回结果 的程序

 心不留意外尘 2016-08-01
http://blog.csdn.net/nomefat/article/details/48788413
2015

  1. import subprocess  
  2. import threading  
  3. import time  
  4. import re  
  5.   
  6. ip_num = 256  
  7. list_ping_result = []  
  8.   
  9. class PingThread(threading.Thread):  
  10.       
  11.     def __init__(self,str_ip,sleep_time,g_list_p_r):  
  12.         threading.Thread.__init__(self)  
  13.         self.sleep_time = sleep_time  
  14.         self.str_ip = str_ip  
  15.         self.list_p_r = g_list_p_r  
  16.     def run(self):  
  17.         time.sleep(self.sleep_time)  
  18.         ftp_sub = subprocess.Popen("ping %s -n 3" % self.str_ip,  
  19.                                   stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True)  
  20.         ret = ftp_sub.stdout.read()  
  21.         str_ret = ret.decode("gbk")  
  22.         ret_s = re.search("TTL",str_ret)  
  23.         if ret_s:  
  24.             self.list_p_r.append(('ping    ok',self.str_ip))  
  25.         else:  
  26.             self.list_p_r.append(('ping error',self.str_ip))  
  27.               
  28. def cmp_s(toupe_str):  
  29.     str_val = toupe_str[1]  
  30.     ret_group = re.match("\d*",str_val[::-1])  
  31.     str_ret = ret_group.group()  
  32.     return int(str_ret[::-1])  
  33.   
  34. thread_id =[]  
  35. for i in range(ip_num):  
  36.     thread_id.append(0)  
  37.     thread_id[i] = PingThread("192.168.8.%d" % i, int(i/20),list_ping_result)  
  38.     thread_id[i].start()  
  39.     print(i,end='')  
  40.   
  41. while True:  
  42.     if len(list_ping_result) >= ip_num:  
  43.         list_ping_result.sort(key=cmp_s)  
  44.         for i in list_ping_result:  
  45.             print(i)  
  46.   
  47.         break  

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约