#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 10线程循环
import telnetlib,threading,queue,time,sys,os,copy

# 调用telnet，输出结果True/False+字符串
def check_port(ip,port):
    command = 'telnet ' + ip + ' '+ port
    try:
        tn = telnetlib.Telnet(ip, port, timeout=10)
    except Exception as e:
        result = (False, command + ' ---Failed: %s\n' % e)
    else:
        result = (True, command + ' ---Passed.\n')
    finally:
        print(result)
        return result

# 调用telnet，输出结果True/False+字符串
def check_port_que():
    ip,port=Qin.get()
    command = 'telnet ' + ip + ' ' + port
    # print(command)
    # 标准的做法是把后面有read / write的部分统统放在一个try 语句里，然后捕获 EOFError 和 socket.error
    try:
        tn = telnetlib.Telnet(ip, port, timeout=10)
    except Exception as e:
        result = (False, command + ' ---Failed: %s\n' % e)
    else:
        result = (True, command + ' ---Passed.\n')
    finally:
        print(result)
        Qout.put(result)

# 分析ip文件，输出ip+端口的list
def ana_ip(iplist):
    address_list=[]
    try:
        f=open(iplist)
        for line in f:
            ip=line.split()[0]
            port_list=line.split()[-1].split('/')
            for port in port_list:
                address_list.append((ip,port))

    except:
        print("ana_ip error!")
    finally:
        # print("ana_ip\n",address_list)
        return address_list

def get_all_item(Q):
    # 可以获取队列Q的所有项，无需等待
    # cq=copy.deepcopy(Q)
    cq=Q
    o_list=[]
    while cq.qsize()>0:
        o_list.append(cq.get_nowait())
    return o_list

# 写log文件
def write_log():
    # 获取python文件名字
    # sys.argv[0].split("/")[-1].split(".")[0]
    py_name=sys.argv[0].split("/")[-1].split(".")[0]
    write_file=py_name+"_output_"+ time.strftime("%Y%m%d_%H%M%S"+".log")
    output = get_all_item(Qout)
    buff = []

    try:
        buff.append('\n---Telnet Failed--------------------------\n')
        for line in output:
            if line[0] == False:
                buff.append(line[1])

        buff.append('\n---Telnet Passed--------------------------\n')
        for line in output:
            if line[0] == True:
                buff.append(line[1])

        f=open(write_file,'w')
        f.writelines(buff)

    except Exception as e:
        print("write_log() error:%s!" % e)
    else:
        f.close()

Qin = queue.Queue()
Qout = queue.Queue()
Qerr = queue.Queue()
Pool = []

def main():
    # 指定ip文件
    input_file=['ip_list','ip_biglist']
    address_list=ana_ip(input_file[1])

    # 填充队列
    for item in address_list:
        Qin.put(item)

    # 记录开始时间
    t_start=time.strftime("%Y-%m-%d %H:%M:%S")
    print("起始队列长度:",Qin.qsize())
    print("start at %s" % t_start)

    #  当队列大于0时, 启动最多10个线程
    while Qin.qsize()>0:
        for i in range(10):
            t=threading.Thread(target=check_port_que)
            t.setDaemon(True)
            Pool.append(t)
            t.start()

        # 阻塞线程
        for i in range(10):
            Pool[i].join()

    # 记录结束时间
    t_end = time.strftime("%Y-%m-%d %H:%M:%S")
    print("start at %s, \nEnd at %s." % (t_start, t_end))
    write_log()

if __name__ == "__main__":
    main()
