3

Everyone, hello!

I'm currently trying to use Telnetlib (https://docs.python.org/2/library/telnetlib.html) for Python 2.7 to communicate with some external devices.

I have the basics set up:

import sys
import telnetlib
tn_ip = xxxx
tn_port = xxxx
tn_username = xxxxx
tn_password = xxxx

searchfor = "Specificdata"

def telnet():
    try:
        tn = telnetlib.Telnet(tn, tn, 15)
        tn.set_debuglevel(100)
        tn.read_until("login: ")
        tn.write(tn_username + "\n")
        tn.read_until("Password: ")
        tn.write(tn_password + "\n")
        tn.read_until(searchfor)
        print "Found it!"
    except:
        print "Unable to connect to Telnet server: " + tn_ip

telnet()

And I'm trying to go through all of the data it's outputting (which is quite a lot) until I catch what I need. Although it is logging in quite fine, and even finds the data I'm looking for, and prints my found it message, I'm trying for a way to keep the connection with telnet open as there might be other data (or repeated data) i would be missing if I logged off and logged back in.

Does anyone know how to do this?

vabada
  • 1,738
  • 4
  • 29
  • 37
user5740843
  • 1,540
  • 5
  • 22
  • 42
  • Do you have a list of specific pieces of information that you need, or do you just want the Telnet connection to stay open indefinitely? – VergeA Oct 12 '16 at 17:21
  • Thank you for your comment! I am looking for several pieces of information. When triggered, something else will be activated, so I would really like to keep the connection open, while scanning at the same time. – user5740843 Oct 12 '16 at 19:31
  • You could make the telnet connection object an instance variable of a class. During construction/initialization of the class, perform the login procedures, and then you can call the read_until() method as many times as you need to by delegating to the instance variable. When the class is destructed/when you don't need the connection anymore, close it. – VergeA Oct 12 '16 at 19:56

1 Answers1

2

Seems like you want to connect to external device once and print a message each time you see a specific string.

import sys
import telnetlib
tn_ip = "0.0.0.0"
tn_port = "23"
tn_username = "xxxxx"
tn_password = "xxxx"

searchfor = "Specificdata"


def telnet():
    try:
        tn = telnetlib.Telnet(tn_ip, tn_port, 15)
    except:
        print "Unable to connect to Telnet server: " + tn_ip
        return
    tn.set_debuglevel(100)
    tn.read_until("login: ")
    tn.write(tn_username + "\n")
    tn.read_until("Password: ")
    tn.write(tn_password + "\n")
    while True:
        tn.read_until(searchfor)
        print "Found it"

telnet()
preezzzy
  • 598
  • 5
  • 23