There's a python library for telnet connections that reads and writes from/to a telnet connection.
Check the link. It has some basic examples of what you are looking for.
Here's an example from the link:
import getpass
import sys
import telnetlib
HOST = "localhost"
user = raw_input("Enter your remote account: ")
password = getpass.getpass()
tn = telnetlib.Telnet(HOST)
tn.read_until("login: ")
tn.write(user + "\n")
if password:
tn.read_until("Password: ")
tn.write(password + "\n")
tn.write("ls\n")
tn.write("exit\n")
print tn.read_all()
It connects to a telnet server. Sends your login credentials and then executes the unix command ls
. Then exits the session and prints all output from the telnet server.