Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

telnetlib python read_all() not working(hangs)

I am trying to read from a cisco router using telnetlib

import telnetlib
tn = telnetlib.Telnet(’10.106.218.50’, 17280)
cmd1=”enable”
cmd2=”show run”
#session.write("command".encode('ascii') + b"\r")
tn.write(cmd1.encode('ascii') + b"\r")
tn.write(cmd2.encode('ascii') + b"\r")
#op=tn.read_very_eager()
#op=tn.read_some()
#op=tn.read_until('#')
op=tn.read_all()
print op

I am able to write to the console of the router successfully However the system just hangs,when i try to read from the console of the router. When i use read_some(), i get a part of the output.But read_all() just hangs and gives no response Please suggest a solution

like image 596
fsociety Avatar asked Apr 29 '26 06:04

fsociety


2 Answers

the

read_all()

command in python's telnetlib module will block if there's no timeout specified when you make your connection.

your invocation command should look like

tn = telnetlib.Telnet('10.106.218.50', 17280, timeout = 1)

you can also substitute your own timeout value.

like image 154
Jiynx Avatar answered Apr 30 '26 19:04

Jiynx


Solution for me was using tn.red_until(). This code works for me. And If you don't need to send the output to text file, then modify:

data = data + tn.read_until(b"FIN\n", timeout = TIMEOUT).decode('ascii')

by:

tn.read_until(b"FIN\n", timeout = TIMEOUT)

Here is my code:

import sys
import telnetlib
import time

username = "admin"
password = "admin"
command = "show version"
TIMEOUT = 3

router_list = open("hostlist.txt")
for line in router_list:
    tn = telnetlib.Telnet(line.rstrip())
    tn.set_debuglevel(1)
    time.sleep(2)
    data = data + tn.read_until(b"Username: ").decode('ascii')
    tn.write(username.encode('ascii') + b"\n")
    time.sleep(2)
    data = data + tn.read_until(b"Password: ").decode('ascii')
    tn.write(password.encode('ascii') + b"\n")
    time.sleep(2)
    tn.write(command.encode('ascii') + b"\n")
    time.sleep(2)
    tn.write(b"\n")
    time.sleep(2)
    tn.write(b"echo FIN\n")
    time.sleep(2)
    data = data + tn.read_until(b"FIN\n", timeout = TIMEOUT).decode('ascii')
    print("Imprimiendo:" + data)
    op=open ("output.txt", "a").write(data)
    tn.close()
like image 42
juanpb12 Avatar answered Apr 30 '26 18:04

juanpb12



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!