3

I am writing python script to automate some task in simulator... to connect to simulator command is telnet localhost <port>.

This command I am giving through os.system(telnet localhost <port>).

It is working.

And simulator is running:

Trying ::1...
Connected to localhost.
Escape character is '^]'.
>

Now I have to give commands through python inside this but I can't inside this(>) I have to give..I used telnet commands but it didn't work.

#!/usr/bin/env python
import os,re,telnetlib
host = "localhost"
port = "1111"

tn = telnetlib.Telnet(host, port)
tn.write("exit")

This is sample code but it is not working.

CAmador
  • 1,881
  • 1
  • 11
  • 19
chitra
  • 79
  • 1
  • 7
  • You seem to mention two different ways to open a telnet session, `os.system('telnet localhost ')` and `tn = telnetlib.Telnet(host, port)`. The second way seems more idiomatic to me, but you are saying that "it is not working"? Can you explain *how* is it not working? – Imperishable Night Jun 25 '19 at 06:28
  • after connecting to telnet my simulator will run ...we have to give commands inside this > ....but unable to write using tn.write – chitra Jun 25 '19 at 06:34

2 Answers2

2

Write command needs the content to be provided in bytes. Try this:

import os,re,telnetlib

host = "google.com"
port = "80"

telnet_client = telnetlib.Telnet(host, port)
print('Connection established')

telnet_client.write(b'exit')
print('<END/>')
  • this is used for connecting to a localhost..but i am using telnet localhost 2222 command to run simulator....after this command Trying ::1... Connected to localhost. Escape character is '^]'. > it has to come like this but i am not getting it – chitra Jun 25 '19 at 06:43
  • Have you checked the firewall and the antivirus? Depending on the configuration they can reject connections. – Frank CNatra Jun 26 '19 at 12:52
2

You might need to tell telnetlib to read until the prompt and then write the command you want to issue.

import os,re,telnetlib
host = "localhost"
port = "1111"

tn = telnetlib.Telnet(host, port)
tn.read_until(b">", timeout=10) # <- add this line
# tn.read_until(b"> ", timeout=10) # if prompt has space behind
tn.write(b"exit\n")

You might also find this question helpful: Python Telnetlib read_until '#' or '>', multiple string determination?

z11i
  • 951
  • 11
  • 26
  • i added that line but i am getting error ...............................telnet.read_until('>', timeout=10) File "/usr/lib64/python3.7/telnetlib.py", line 302, in read_until i = self.cookedq.find(match) TypeError: argument should be integer or bytes-like object, not 'str' – chitra Jun 25 '19 at 06:49
  • @lokeswari you're using Python 3, the telnetlib expects bytes or ints which is the error you got. I've updated my answer accordingly. – z11i Jun 25 '19 at 06:55
  • i am not getting any errors using this ..but my simulator is not running and unable to give exit command – chitra Jun 25 '19 at 07:00