python编写telnet登陆出现TypeError:'str' does not support the buffer interface

python3支持byte类型,python2不支持。在python3中,telnet客户端向远程服务器发送的str要转化成byte,从服务器传过来的byte要转换成str,但是在python2不清楚怎么回事。。。解决方法:

1.用python2的编译器

2.str对象和bytes对象可以使用.encode() (str -> bytes) or .decode() (bytes -> str)方法相互转化

>>> b = b'china' 
>>> type(b) 
<type 'bytes'>
>>> s = b.decode() 
>>> s 
'china' 
>>> b1 = s.encode() 
>>> b1 
b'china'

附上具体的代码:
tn.read_until(b'login:')//读取到二进制字符串
    tn.write((username + '\n').encode())//将字符串变成二进制字符串发送出去
    #输入密码
    tn.read_until(b'Password:')
    tn.write((password + '\n').encode())
如果有要输入的命令,也要转化成二进制字符串发送出去。比如configure 要b'configure
 

posted on 2016-07-04 22:46  IT_宅  阅读(242)  评论(0编辑  收藏  举报

导航