Search code examples
pythonpython-3.xtelnettelnetlib

TypeError: 'in <string> while send cmd via python telnet


I tried to send ls / cmd via python telnet

import telnetlib
tel = telnetlib.Telnet('10.10.0.1'.'1234')
tel.write('ls / ')

But I got an error :

if IAC in buffer:
TypeError: 'in <string>' requires string as left operand, not bytes

Solution

  • You need to encode your string to ASCII:

    tel.write(('ls / ').encode('ascii'))
    

    In Python3, str class stores strings as unicode, you need to explicitly convert them to ascii. You basically need a byte-string with every character as an ASCII character rahter than a Unicode one.