Search code examples
pythonbackslashtelnetlib

Using telnetlib - backslash is doubled in 'tn.write' (but not in 'print') - how to send single backslash in my write string


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?


Solution

  • 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")