JonStanley91 JonStanley91 - 4 months ago 27
Python Question

Telnet not working for os.system call

Why cant I call the following in python using os?

import os
os.system('telnet 1.1.1.1')


yet when I open a terminal and use the exact command, I can telnet. I get the following when running the code:


'telnet' is not recognized as an internal or external command,
operable program or batch file.


I have enabled TelnetClient and TelnetServer

mK7 mK7
Answer

@Jon S.: Programs like Telnet and SSH are interactive in nature. So when you open a telnet it will return something from the shell it is running to handle that particular connection. I haven't tried running the command like you mentioned above but I have used 'telnetlib' of python in Windows successfully in the past and still using it. Here is a snippet that can be of help.

import telnetlib
import os

host_ip = "1.1.1.1"
user = "user"
password = "password"

tnet_hndl = telnetlib.Telnet(host_ip)
print (tnet_hndl.read_until(b"login: "))
tnet_hndl.write(user.encode('ascii') + b"\n")
print (tnet_hndl.read_until(b"Password: "))
tnet_hndl.write(password.encode('ascii') + b"\n")
print (tnet_hndl.read_until(b"# "))
#tnet_hndl.set_debuglevel(1) #enable this if you want to debug more
tnet_hndl.write(b"<enter some windows cmd here>" + b"\n")
print (tnet_hndl.read_until(b"# "))
tnet_hndl.close()

Hope this helps.

Comments