Python 2和unicode_literals - UnicodeDecodeError:' ascii'编解码器不能解码字节

时间:2018-02-19 02:37:44

标签: python unicode-literals

Super duper Python newb here。明确学习网络自动化。我一直试图做的一件事就是使代码既可以在Python2和Python3中运行,但我遇到的问题对于大多数人来说可能是显而易见的。是的,这里的标题与我找到的this post相同。但是据我所知,我已经完成了建议(通过.format()将变量粘贴到write语句中)

这是代码..

#!/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())

这就是我在运行时遇到的错误....

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)

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。使用telnetlib库时导入unicode_literals是错误的。我需要在相反的方向上格式化它,明确地为ascii字符设置python3。更正后的代码如下

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