2

I'm trying to send command in tetnet but it's not working. i tried different code find in this forum but no one works. it's for rebooting a device. i'm using python 3.6.

import telnetlib

host = "192.168.1.0"
port = 23
timeout = 100

session = telnetlib.Telnet(host, port, timeout)
session.write("administrator\n").encode('ascii')
session.write("password\n").encode('ascii')
session.write("reboot\n").encode('ascii')
Ondrej K.
  • 8,841
  • 11
  • 24
  • 39
Micky
  • 1,295
  • 3
  • 8
  • 5
  • Have you considered using pexpect? With pexpect, you can conditionally specify the next action. Your case is very straight forward, so it may be overkill, but I would suggest learning pexpect since it is way more flexible. – Mark Jul 09 '18 at 15:42

2 Answers2

3

The Telnet.write() function takes a byte string. This can either be supplied by encoding just the string (you tried encoding the return from the function), e.g.

session.write("administrator\n".encode('ascii'))

or by prefixing your strings with b as follows:

import telnetlib

host = "192.168.1.0"
port = 23
timeout = 100

with telnetlib.Telnet(host, port, timeout) as session:
    session.write(b"administrator\n")
    session.write(b"password\n")
    session.write(b"reboot\n")
Martin Evans
  • 45,791
  • 17
  • 81
  • 97
0

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.