to connect and use the telnet protocol you can use telnetlib when you can install it using pip3 install telnetlib3
, in my case I am using ubuntu 22.. and it is work 100% with no issues,
import telnetlib
class TelnetFunction:
def __init__(self, host, port, username, password) -> None:
self.connect(host, port, username, password)
def connect(self, host, port, username, password):
self.tn = telnetlib.Telnet(host, port)
self.tn.read_until(b"login: ")
self.tn.write(username.encode('ascii') + b"\n")
if password:
self.tn.read_until(b"Password: ")
self.tn.write(password.encode('ascii') + b"\n")
print(self.executCommand(""))
def isConnected(self):
return self.tn.sock.fileno()
def executCommand(self, command):
self.tn.write(command.encode('ascii'))
output = self.tn.read_until(b"$ ").decode('utf-8')
return output
def close(self):
self.tn.close()
and for using this class try this code:
host = "your_host" #example 192.168.1.12
username = "username_machin" #username of your machine on Ubuntu you can use "whoami" in CLI
password = "*******"#password of your machin
port = 23 #the used port
tn = TelnetFunction(host, port, username, password)
tn.executCommand(input('your command: ')+'\b') #execute your command in the server
tn.close() #close the connection with the server
if you got any problem let me know.