python telnet 登录

发布时间:2019-09-15 10:01:33编辑:auto阅读(2359)

    有段时间想利用python自动批量登录设备,并输入命令。

    但是读取设备列表文件遍历后发现telnetlib库的登录不上设备。其显示错误为

    socket.gaierror: [Errno 4] non-recoverable name resolution failure

     

    明显是DNS解析IP地址错误。

     

    把设备名列表文件全部改成IP地址的话能正常登录。

     

    如果把登录用的host参数手工输入的话可以正常登录设备。

     

    经len函数对比读取的文件和手工输入的设备名的字段后发现其长度差1个字符。说明用for读取设备列表后每个设备名后多了个换行符。我只需要每次从设备名列表读取设备名后删掉最后一个字符,也就是换行符就可以正常登录了。

    #!/usr/bin/env python
    import subprocess
    import telnetlib
    import time
    import getpass
    f = open("list.txt")
    line = f.readlines()
    username = raw_input("Username:")
    password = getpass.getpass("Password: ")
    def telnet(username,password,Host):
        tn = telnetlib.Telnet(Host,port =23,timeout =10)
    #    tn.set_debuglevel(2)
        tn.read_until('Username:')
        tn.write(username + '\n')
        tn.read_until('Password:')
        tn.write(password + '\n')
        print tn.read_until('>')
        tn.write('screen-length 0 temporary'+ "\n")
        print tn.read_until('>')
        tn.write('display aaa route all'+'\n')
        print tn.read_until('>')
        tn.close()
    for Host in line:
        Host = Host[0:len(Host)-1]      #此处说明读取设备列表后只提取到倒数第一个字符,也就是删除换行符
        telnet(username,password,Host)
    f.close()

     

关键字