Problems with buffer telnetlib on python

I'm developing a software which make telnet connections to send the scripts to the routers. I need to save the logs of each router in txt files but at the end the shows commands saves are incomplete, especially the commands that have a longer output as (show run). I configured the vty lines , the command (length 512), however these commands continue to be recorded in the files incomplete. I was thinking that is a problem about the buffer, is there a way to configure the max of the buffer or it could be another problem?"

I hope you can help me, thanks.

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"

Example

enter image description here

Upvotes: 0

Views: 1336

Answers (1)

quemeraisc
quemeraisc

Reputation: 492

The problem here is that the output you get is too long. In interacive mode you'll have a "more" at the end of each page. Cisco allows you to set the length of the terminal, size of the page if you like ; '0' means no-more. You can send a "terminal length 0" as a very first command. After that all your program will get the full output, thus avoiding to hang, waiting for someone to key something in.

Upvotes: 1

Related Questions