Search code examples
pythonpython-2.7moduletelnetlib

How do i search with re in a telnet session output?


import getpass
import sys
import telnetlib
import re
import smtplib

print "Pasul 1"

HOST = "route-views.routeviews.org"
user = "rviews"
password = ""

tn = telnetlib.Telnet(HOST)

tn.read_until("login: ", 5)
tn.write(user + "\r\n")

tn.read_until("Password: ", 5)
tn.write(password + "\r\n")

print tn.read_until(">", 10)
y = str(tn.write("show ip route 192.0.2.1"+"\r\n"))

print tn.read_until("free", 10)
tn.write("exit"+ "\r\n")

tn.close()

print "Pasul 2"

m = re.search('Last', y)
if m:
    print (m.group(0))
else:
    print False

Anything i search in the output it returns me False. Why? It should return the word.

This is the output:

Pasul 1

route-views> show ip route 192.0.2.1

Routing entry for 192.0.2.1/32

Known via "bgp 6447", distance 20, metric 0

Tag 19214, type external

Last update from 208.74.64.40 4w0d ago

Routing Descriptor Blocks:

  • 208.74.64.40, from 208.74.64.40, 4w0d ago

    Route metric is 0, traffic share count is 1

    AS Hops 1

    Route tag 19214

    MPLS label: none

route-views>

Pasul 2

False


Solution

  • You need to store the string from the telnet session into y for this to work. Currently, you are storing "show ip route 192.0.2.1\r\n" in y due to this line:

    y = str(tn.write("show ip route 192.0.2.1"+"\r\n"))

    In order to do what you are intending, you must store the tn.read_until("free", 10) to be able to search it later. Currently, you are just printing it out.

    Example replace:

    print tn.read_until("free", 10)
    

    with

    y = tn.read_until("free", 10)
    print y