fcs1000
fcs1000

Reputation: 21

Python 2 and unicode_literals - UnicodeDecodeError: 'ascii' codec can't decode byte

Super duper Python newb here. Learning explicitly for network automation. One thing I've been trying to do is make code that works both in Python2 and Python3 but I've run into an issue that is probably obvious to most. And yes the title here is the same as this post that I found. However as far as I can tell, I've done what was suggested (sticking variable into the write statement via .format())

Here is the code..

#!/usr/bin/env python

from __future__ import print_function, unicode_literals
import getpass
import telnetlib

#Ask for username/pass
host_ip = '192.168.122.200'

try:
    #For Py2
    username = raw_input('Enter your telnet username: ')
except NameError:
    #For Py3
    username = input('Enter your telnet username: ')

password = getpass.getpass()

tn = telnetlib.Telnet(host_ip)

tn.read_until('Username: ')
tn.write('{}\n'.format(username))
if password:
    tn.read_until('Password: ')
    tn.write('{}\n'.format(password))

tn.write('terminal length 0\n')
tn.write('show version\n')
tn.write('exit\n')

print(tn.read_all())

And here's the error I'm getting when running it....

root@NetworkAutomation-1:~# python get_show_version.py 
Enter your telnet username: chase
Password: 
Traceback (most recent call last):
  File "get_show_version.py", line 22, in <module>
    tn.write('{}\n'.format(username))
  File "/usr/lib/python2.7/telnetlib.py", line 280, in write
    if IAC in buffer:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 0: ordinal not in range(128)

Upvotes: 2

Views: 894

Answers (1)

fcs1000
fcs1000

Reputation: 21

I figured out the solution. Importing unicode_literals when using the telnetlib library is the wrong thing to do. I needed to format it in the opposite direction, setting up python3 for ascii characters explicitly. Corrected code is as follows

#!/usr/bin/env python

from __future__ import print_function
import getpass
import telnetlib

#Ask for username/pass
host_ip = '192.168.122.200'

try:
    #For Py2
    username = raw_input('Enter your telnet username: ')
except NameError:
    #For Py3
    username = input('Enter your telnet username: ')

password = getpass.getpass()

tn = telnetlib.Telnet(host_ip)

tn.read_until(b'Username: ')
tn.write(username.encode('ascii') + b'\n')
if password:
    tn.read_until(b'Password: ')
    tn.write(password.encode('ascii') + b'\n')

tn.write(b'terminal length 0\n')
tn.write(b'show version\n')
tn.write(b'exit\n')

print(tn.read_all().decode('ascii'))

Upvotes: 0

Related Questions