chitra
chitra

Reputation: 89

How to give commands inside telnet session using python

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.

Upvotes: 3

Views: 5774

Answers (2)

z11i
z11i

Reputation: 1296

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?

Upvotes: 2

fcnatra
fcnatra

Reputation: 21

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/>')

Upvotes: 2

Related Questions