# conding:utf8
#ping  ip网段并将结果写入文件
import subprocess
import threading
import time
import re
ip_num = 256
list_ping_result = []
tm=time.strftime('%Y-%m-%d %H:%M:%S')
ip_ture=open('HOSTNAME_PING.txt','w',encoding='utf8')
ip_ture.write('以下为ip段ping后结果:【ok:可以ping通,error:ping不通】'+'\n')
ip_ture.write('序号  ping结果          IP               时间'+'\n')
count_True, count_False = 0, 0
print('请输入要ping网段的IP前三位,如‘192.168.0')
ip_input= input('输入要ping的网段:')
print('Ping Processing, Please Wait...')
class PingThread(threading.Thread):
    def __init__(self, str_ip, sleep_time, g_list_p_r):
        threading.Thread.__init__(self)
        self.sleep_time = sleep_time
        self.str_ip = str_ip
        self.list_p_r = g_list_p_r
    def run(self):
        time.sleep(self.sleep_time)
        ftp_sub = subprocess.Popen("ping %s -n 3" % self.str_ip,stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True)
        ret = ftp_sub.stdout.read()
        str_ret = ret.decode("gbk")
        ret_s = re.search("TTL", str_ret)
        if ret_s:
            self.list_p_r.append(('ping    【ok】', self.str_ip))
        else:
            self.list_p_r.append(('ping 【error】', self.str_ip))
def cmp_s(toupe_str):
    str_val = toupe_str[1]
    ret_group = re.match("\d*", str_val[::-1])
    str_ret = ret_group.group()
thread_id = []
for i in range(ip_num):
    thread_id.append(0)
    thread_id[i] = PingThread(ip_input+".%d" % i, int(i / 10), list_ping_result)
    thread_id[i].start()
while True:
    if len(list_ping_result) >= ip_num:
        list_ping_result.sort(key=cmp_s)
        for i in list_ping_result:
            print(i)
            ip_ture.write(str(count_True)+'     '+str('  '.join(i))+'    ' + tm + '\n')
            count_True +=1
        break
print('操作结束')