#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 单线程telnet
import telnetlib
import string
import sys,os


# 调用telnet，输出结果True/False+字符串
def check_port(ip,port):
    address = 'telnet ' + ip + ' '+ port
    try:
        tn = telnetlib.Telnet(ip, port, timeout=10)
        result = (True,address + ' ---Passed\n')
    except:
        result = (False,address + ' ---Failed\n')
    finally:
        print("check_port: ",result)
        return 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 main():
    result_list=[]
    address_list=ana_ip('ip_biglist')

    for i in address_list:
        result=check_port(i[0],i[1])
        result_list.append(result)

    # # 写log文件
    # if ( not os.path.exists("ip_result")):
    #     os.mknod("ip_result")

    try:
        f=open('ip_result','w')

        # 记录telnet失败地址
        f.write('\n---Telnet Failed--------------------------\n')
        for line in result_list:
            if line[0] == False:
                f.write(line[1])

        # 记录telnet通过地址
        f.write('---Telnet Passed--------------------------\n')
        for line in result_list:
            if line[0]==True:
                f.write(line[1])
    except:
        print("main error!")
    finally:
        f.close()

if __name__ == "__main__":
	main()