0

I'm trying to telnet a string to a server using Python 2.7 (in Windows).

The application requires backslashes in the string like this: 'E\myMacro\\', so it needs a single backslash within it, and ends with double backslash.

I have been successful using the cmd module but have failed in Python 2.7.

Here's the code:

import telnetlib
host = "myHost"
tn = telnetlib.Telnet(host)
tn.set_debuglevel(100)
data = tn.read_until("server")

myLine = r'E\myMacro'+'\\\\'

tn.write(myLine)
tn.close()

print myLine

This is my output:

Telnet(myHost,23): recv 'Welcome to the server'
Telnet(myHost,23): send 'E\\myMacro\\\\'
E\myMacro\\

I've tried every permutation I can think of to create the string but without success.

Can anyone explain what I'm doing wrong? Why is there a difference between tn.write and print?

Eric Scroggins
  • 47
  • 1
  • 2
  • 6
  • Cannot test the telnet communication, but I have noticed that `r'E\\myMacro'` is a raw string, i.e. there should be only one backslash in that string. – VPfB Jan 10 '19 at 13:10
  • What is weird is the message `Telnet(myHost,23): send 'E\\myMacro\\\\'`. Because `'\\\\'` is the same as `r'\\'` and only contains 2 backslashes. And the first part `r'E\\myMacro'` also contains 2 backslashes because of the initial `r`. – Serge Ballesta Jan 10 '19 at 13:22
  • Thank you both! I realise I have made a typo here, so I've edited the post. As you've pointed out the line should have read myLine = r'E\myMacro'+'\\\\'. And as if that wasn't enough, I also misled you on the output - print gives E\myMacro\\ (also amended above) – Eric Scroggins Jan 10 '19 at 17:17
  • try Telnet(myHost,23): send 'E\\myMacro\/\' – NiallJG Jan 10 '19 at 17:20

1 Answers1

0

I've solved my problem, in the end it proved to be a very simple fix:

import telnetlib
host = "myHost"
tn = telnetlib.Telnet(host)
myLine = 'E\myMacro'
tn.write(myLine+'\\\\\r\n')
tn.write("exit\n")
Eric Scroggins
  • 47
  • 1
  • 2
  • 6