Telnet.read.until函数不起作用

时间:2013-12-10 02:36:25

标签: python-3.x

尝试telnet到Brocade路由器并且python脚本发送错误....不确定这里有什么问题。尝试过调试,但无法使其正常工作。我相信这是一个及时的问题。如果有人建议如何让它发挥作用我感激不尽。

注意:这是Python 3.0

import getpass
import sys
import telnetlib

HOST = "1.1.1.1"
user = "admin"
password = "password"
port = "23"

telnet = telnetlib.Telnet(HOST)

telnet.read_until("sw0 login:,3")

telnet.write(admin + "\r")
if password:
    telnet.read_until("Password: ")
    telnet.write(password + "\n")

tn.write("term len 0" + "\n")
telnet.write("sh ver br\n")
telnet.write("exit\n")


ERROR:

Traceback (most recent call last):
  File "C:\Users\milan\Desktop\telnetNew.py", line 13, in <module>
    telnet.read_until("Username :,3")
  File "C:\Python33\lib\telnetlib.py", line 299, in read_until
    return self._read_until_with_select(match, timeout)
  File "C:\Python33\lib\telnetlib.py", line 352, in _read_until_with_select
    i = self.cookedq.find(match)
TypeError: Type str doesn't support the buffer API


This is my prompt after logging manually using telnet port 23 and this is what i expected command to work.
_________________________________________________________________________________



Network OS (sw0)
xxxxxxxxxx


sw0 login: xxxxx
Password:  xxxxx

WARNING: The default password of 'admin' and 'user' accounts have not been changed.

Welcome to the Brocade Network Operating System Software
admin connected from 10.100.131.18 using console on sw0
sw0# sh ver


sw0#

4 个答案:

答案 0 :(得分:5)

在查看文档时,似乎telnetlib需要bytestr,而不是Str。所以尝试这个。,它应该将所有内容转换为字节而不是Str

import sys
import telnetlib

HOST = "1.1.1.1"
user = "admin"
password = "password"
port = "23"

telnet = telnetlib.Telnet(HOST,port)
telnet.read_until(b"login: ")

telnet.write(admin.encode('ascii') + b"\n")
telnet.read_until(b"Password: ")
telnet.write(password.encode('ascii') + b"\n")

tn.write(b"term len 0\n")
telnet.write(b"sh ver br\n")
telnet.write(b"exit\n")

- 编辑 - 我安装了python并尝试对付我的一个路由器。将用户名/密码更改为我的凭据我能够正常登录。 (我删除了密码检查和getpass,因为它们没有被使用,因为你的代码是硬编码的)。看起来你复制了2.x示例,但3.x要求缓冲区兼容的没有b“我得到这个

Traceback (most recent call last):
  File "foo.py", line 5, in <module>
    telnet.read_until("login: ")
  File "/usr/local/Cellar/python32/3.2.5/Frameworks/Python.framework/Versions/3.2/lib/python3.2/telnetlib.py", line 293, in read_until
    return self._read_until_with_poll(match, timeout)
  File "/usr/local/Cellar/python32/3.2.5/Frameworks/Python.framework/Versions/3.2/lib/python3.2/telnetlib.py", line 308, in _read_until_with_poll
    i = self.cookedq.find(match)
TypeError: expected an object with the buffer interface

用b“我得到

[~] /usr/local/bin/python3.2 foo.py
b'\r\n\r\nThis computer system including  all related equipment, network devices\r\n(specifically  including  Internet  access),  are  provided  only  for\r\nauthorized use.  All computer

表明它正在运作..你现在有什么错误

答案 1 :(得分:2)

import telnetlib , socket


class TELNET(object):

    def __init__(self):
        self.tn = None
        self.username = "root"
        self.password = "12345678"
        self.host = "10.1.1.1"
        self.port = 23
        self.timeout = 5
        self.login_prompt = b"login: "
        self.password_prompt = b"Password: "

    def connect(self):
        try :
            self.tn = telnetlib.Telnet(self.host,self.port,self.timeout)
        except socket.timeout :
            print("TELNET.connect() socket.timeout")

        self.tn.read_until(self.login_prompt, self.timeout) 
        self.tn.write(self.username.encode('ascii') + b"\n")

        if self.password :
            self.tn.read_until(self.password_prompt,self.timeout)
            self.tn.write(self.password.encode('ascii') + b"\n")

    def write(self,msg):
        self.tn.write(msg.encode('ascii') + b"\n")
        return True


    def read_until(self,value):
        return self.tn.read_until(value)


    def read_all(self):
        try :
            return self.tn.read_all().decode('ascii')
        except socket.timeout :
            print("read_all socket.timeout")
            return False

    def close(self):
        self.tn.close()
        return True


    def request(self,msg):
        self.__init__()
        self.connect()
        if self.write(msg) == True :
            self.close()
            resp = self.read_all()
            return resp
        else :
            return False

telnet = TELNET()

#call request function 

resp = telnet.request('ps www') # it will be return ps output
print(resp) 

该代码适用于python3

答案 2 :(得分:2)

这些答案中的大多数都是非常深入的解释,我发现它们有点难以理解。简短的回答是Python 3x站点上的示例代码错误。

解决这个问题,而不是 'telnet.read_until(“用户名:,3”)' 使用 'telnet.read_until(b“用户名:,3”)'

答案 3 :(得分:1)

与其他答案一样,问题是Telnetlib需要字节字符串。在Python 2中,str类型是一个字节字符串(一串二进制数据),而它是Python 3中的一个unicode字符串,另一个表示二进制数据的新bytes类型是{{1在Python 2中做过。

这样做的结果是,在Python 3中使用Telnetlib时,您需要将str数据转换为str数据。我有一些代码可以在Python2和Python3中使用,我认为值得分享。

bytes

然后,您实例化新的class Telnet(telnetlib.Telnet,object): if sys.version > '3': def read_until(self,expected,timeout=None): expected = bytes(expected, encoding='utf-8') received = super(Telnet,self).read_until(expected,timeout) return str(received, encoding='utf-8') def write(self,buffer): buffer = bytes(buffer, encoding='utf-8') super(Telnet,self).write(buffer) def expect(self,list,timeout=None): for index,item in enumerate(list): list[index] = bytes(item, encoding='utf-8') match_index, match_object, match_text = super(Telnet,self).expect(list,timeout) return match_index, match_object, str(match_text, encoding='utf-8') 类而不是Telnet。新类重写了Telnetlib中的方法,以执行从telnetlib.Telnetstrbytesbytes的转换,以便问题消失。

当然,我只是覆盖了我正在使用的方法,但是从示例中应该清楚如何将这个想法扩展到其他方法。基本上,你需要使用

str

 bytes(str_string, encoding='utf-8')

我的代码是有效的Python 2和3,因此可以使用任何解释器进行修改。在Python2中,会跳过覆盖方法的代码,实际上会被忽略。如果您不关心向后兼容性,则可以删除检查Python版本的条件。