telnet可登录批量检测

本脚本用于批量检测telnet可登录

思路

telnet验证方法1使用telnetLib,速度快,win和linux通用
方法2使用pexpect,相对慢一些,linux专用

代码

import pexpect
import telnetlib
from multiprocessing.dummy import Pool

inputFile='telnet_final.txt'
outputFile='telnet_final_607.txt'


#验证方法1
def telnetConnect(Host,Port):
    print('***************host:'+Host+'    port'+Port)
    # try:
        # 连接Telnet服务器
    try:
        tn = telnetlib.Telnet(Host, port=Port, timeout=10)

        tn.set_debuglevel(2)
    except:
        print("超时!")
        return False
        # 输入登录用户名
    result = tn.read_until(b'ogin',timeout=5)

    result = str(result)

    print('ddddddddddddddddddddddddd' + result)
    # except:
    #     print('网络不通')
    #     return False

    result = str(result)
    print(result)

    if 'login' in result or 'Login' in result or 'ser' in result or 'assword' in result:
        return True
    else:
        return False

#验证方法2
def telnet(hostname,port):
    cmd='telnet '+hostname+' '+port
    process = pexpect.spawn(cmd, timeout=5)
    #'lose':close
    #'goi':login
    #'ser':user
    #'assword':password
    index = process.expect(['lose', 'ogi','ser','assword', pexpect.TIMEOUT, pexpect.EOF])
    if index == 0:
        return False #访问控制
    elif index == 1:
        return True #可登陆
    elif index ==2:
        return True
    elif index ==3:
        return True
    else:
        return False #访问控制

def infoL(path):
    infoList=[]
    with open(path,'r') as file:
        for eachine in file:
            n = eachine.split()
            ip = n[0]
            port = n[1]
            info={'ip':ip,'port':port}
            infoList.append(info)

    return infoList

def go(info):
    hostname=info['ip']
    port=info['port']
    with open(outputFile,'a+') as file:
        #此处使用方法2
        if telnet(hostname,port) :

            l=hostname+' '+port+' '+'True'
            print(l)
            file.write(l+'\n')
        else:
            l=hostname+' '+port+' '+'False'
            print(l)
            file.write(l+'\n')

if __name__ == '__main__':
    infolist=infoL(inputFile)
    tp=Pool(10)#默认10线程
    tp.map(go,infolist)
    tp.close()
    tp.join()

你可能感兴趣的:(python3Study)