Daniel
Daniel

Reputation: 1650

Open interactive telnet session from Python

I am currently writing a small script in Python which reads some possible connections from a database (triple of node name, telnet IP address and telnet port) and present that to the user to choose to which node to connect.

After this selection I want to open an interactive Telnet session, which can be used by the user as if he had manually connected using the telnet command. Somehow I probably will need an escape sequence for that. It only needs to work on Linux OS.

I could just call telnet:

# Open shell
call(["telnet", selected_node['ip'], selected_node['port']])

That does work. However, I wonder if there might be a better solution.

Upvotes: 3

Views: 3509

Answers (1)

Ivan Velichko
Ivan Velichko

Reputation: 6709

It's python, everything is included. There is a telnet module in the standard library.

import getpass
import telnetlib

HOST = "localhost"
user = input("Enter your remote account: ")
password = getpass.getpass()

tn = telnetlib.Telnet(HOST)

tn.read_until(b"login: ")
tn.write(user.encode('ascii') + b"\n")
if password:
    tn.read_until(b"Password: ")
    tn.write(password.encode('ascii') + b"\n")

tn.write(b"ls\n")
tn.write(b"exit\n")

print(tn.read_all().decode('ascii'))

Upvotes: 2

Related Questions