python上缓冲区telnetlib的问题

时间:2016-04-10 16:22:34

标签: python buffer telnet router telnetlib

我正在开发一个软件,它使telnet连接将脚本发送到路由器。我需要在txt文件中保存每个路由器的日志,但最后show节点保存不完整,尤其是输出较长的命令(show run)。我配置了vty行,命令(长度512),但是这些命令继续记录在文件中。 我在想这是关于缓冲区的问题,有没有办法配置缓冲区的最大值,或者它可能是另一个问题?“

我希望你能帮助我,谢谢。

import telnetlib
import time
import re
from os import listdir
import os.path
import os
global ip
ip = []
global cmd_file
cmd_file= []
global bandera
bandera = 0

def agregardispositivos():     
        numero = input("Inserte la cantidad de equipos a conectar: ")
        return numero

def agregarpuertos(numero):
        ip = []
        for i in range(numero):
             direcciones =raw_input("Ingrese la direccion IP: ")
             ip += [direcciones]
        return ip

def asociarpuerto_router(numero):
        router=[]
        for i in range(numero):
             nombre= "R"+ str(i+1)
             router.append(nombre)
             print router
        return router

def agregararchivo(numero, pregunta):
        #bandera=0
        cmd_file = []
        for root, dirs, files in os.walk("."):
            path = root.split('/')
            if os.path.basename(root) == pregunta:
                for lista in files:
                        archivos=lista
                        cmd_file += [archivos]
        return cmd_file


def realizar_prueba(direccion, TELNET_PORT, TELNET_TIMEOUT, READ_TIMEOUT, respuesta, pregunta):
    try:
       connection = telnetlib.Telnet(direccion, TELNET_PORT, TELNET_TIMEOUT)
       output = connection.read_until("name:", READ_TIMEOUT)
       connection.write('root' + "\n")
       output = connection.read_until("word:", READ_TIMEOUT)
       connection.write('admin123'+ "\n")
       time.sleep(0.2)
       selected_cmd_file= open(respuesta, 'r')
       print selected_cmd_file
       #Starting from the beginning of the file
       selected_cmd_file.seek(0)
       for each_line in selected_cmd_file.readlines():
                connection.write(each_line + '\n')
                time.sleep(0.2)
       #Closing the file
       selected_cmd_file.close()

       #Test for reading command output

       output = connection.read_very_eager()
       band=1
       guardar_salida(output, pregunta,band)

       realizar_show(connection,pregunta)

       #Closing the connection
       connection.close()
       time.sleep(0.2)
    except IOError:
       print "Input parameter error! Please check username, password and file name."

def guardar_salida(output, pregunta,band):
        archive = "Corrida_"+pregunta+".txt"
        f =open(archive, 'a')
        if (band == 1):
                f.write ("***** Configuracion de Router *****\n")
        if (band == 2):
                f.write ("\n\n###### Aplicacion de shows #####\n")
        f.write(output)
        f.close()

def realizar_show(connection,pregunta):
        archivo_show= open('VERIFICATION_STEPS.txt', 'r')
        #Starting from the beginning of the file
        archivo_show.seek(0)
        while True:
                auxar = archivo_show.readline()
                if (re.search("#STEP "+pregunta[5:]+"#", auxar, re.IGNORECASE)):
                        auxar = archivo_show.readline()
                        while auxar != '\n':
                                connection.write(auxar + '\n')
                                connection.write('  ')
                                time.sleep(0.2)
                                auxar = archivo_show.readline()
                        break
                else:
                        archivo_show.readline()

        archivo_show.close()
        output = connection.read_very_eager()
        band=2
        guardar_salida(output, pregunta,band)

#Open telnet connection to devices
def open_telnet_conn(cmd_file, ip): 
           j=0
           numero=agregardispositivos()
           ip=agregarpuertos(numero)

           pregunta = raw_input("Dime la carpeta: ")
           cmd_file=agregararchivo(numero, pregunta)
           print cmd_file
           TELNET_PORT= 23         
           TELNET_TIMEOUT = 5   
           READ_TIMEOUT = 5
           #EL CICLO QUE RECORRE LAS DIRECCIONES IP 
           for direccion in ip:
               #PREGUNTA CONTIENE EL DIRECTORIO (STEP_1 , 2 , 3 , ETC)
               cadena =cmd_file [j]
               respuesta= "./"+pregunta+"/"+cadena+""
               print respuesta

               realizar_prueba(direccion, TELNET_PORT, TELNET_TIMEOUT, READ_TIMEOUT, respuesta, pregunta)
               j=j+1

while True:
    print "1. Ejecutar scripts"
    print "2. Salir"
    opcion = input("Escribir tu opcion: ")
    if opcion ==1:
        #Calling the Telnet function
        open_telnet_conn(cmd_file, ip)
    elif opcion ==2:
        break
    else:
        print "Tu opcion no es valida"

实施例

enter image description here

1 个答案:

答案 0 :(得分:0)

这里的问题是你得到的输出太长了。在交互模式中,您将拥有更多"更多"在每页的末尾。思科允许您根据需要设置终端的长度,页面大小; ' 0'意味着没有更多。 您可以发送"终端长度0"作为第一个命令。之后,您的所有程序都将获得完整的输出,从而避免挂起,等待某人键入内容。