【问题标题】:python3 telnet occur cannot use a string pattern on a bytes-like objectpython3 telnet发生不能在类似字节的对象上使用字符串模式
【发布时间】:2020-04-17 07:42:35
【问题描述】:

我有一些与 python3 中的 telnet 相关的问题。会发生 TypeError:不能在类似字节的对象上使用字符串模式。 有谁知道如何解决这个问题?如果使用python2不会有问题。

代码只是telnet到cisco服务器并打印mac的ipv6地址。

def Telnet_Check_reachability(ip):
ping_count=3
process = subprocess.Popen(['ping', ip, '-n', str(ping_count)],
                       stdout=subprocess.PIPE,
                       stderr=subprocess.STDOUT)

process.wait()
stdout = process.stdout.read()
#print stdout
if "TTL=" in stdout:
    #print "Server reachable"
    successful = 1
else:
    #print "Server unreachable"
    successful = 0
return successful

def telnet_To_CMTS(Client_IP, Client_Name, Client_Pwd, MAC):
    tn =Login_Telnet(Client_IP, Client_Name, Client_Pwd)
    if "telnetlib" in str(tn):
        time.sleep(1)
        value = tn.read_until(b"Router#")
        command = "scm " + MAC + " ipv6\n"
        tn.write(command.encode('ascii') + b"\n")
        #tn.write(command)

        value = tn.read_until(b"Router#")
        #print value
        tn.close()
        time.sleep(1)

        info = "2001"

        #value=str(value)

        matchObj = re.match(r'.*'+ info + '(.*)\n',value, re.M|re.DOTALL)

        if matchObj:
            Ipv6_address = info + matchObj.group(1)
            Ipv6 = Ipv6_address.replace("\n", "")
            return Ipv6
        else:
           print ("No match!!")    


    else:
        print ("Telnet failed")


ip ="192.168.1.252"
username = "guest"
password = "guest"
mac = "xxxx.bbbb.cccc"
new_IPv6 = telnet_To_CMTS(ip, username, password, mac)
#print (new_IPv6)

【问题讨论】:

  • 你能添加整个引用吗?
  • 文件“telnet_CMTS2.py”,第 16 行,在 Telnet_Check_reachability 中,如果标准输出中的“TTL=”:TypeError:需要类似字节的对象,而不是“str”

标签: python python-3.x


【解决方案1】:

telnet 实例的read_until 方法返回bytes,而不是str,因此在将value 传递给正则表达式之前,您需要对其进行解码:

    value_bytes = tn.read_until(b"Router#")

    # Decode value_bytes to str.  The encoding is *probably* ASCII
    value = value_bytes.decode('ascii')

    tn.close()
    time.sleep(1)

    info = "2001"

    matchObj = re.match(r'.*'+ info + '(.*)\n',value, re.M|re.DOTALL)

或者,您可以将value 保留为bytes,并将info 和正则表达式模式编码为bytes,但通常将bytes 转换为str,反之亦然您的应用程序,除非您纯粹使用 bytes

【讨论】:

  • 我已经更新了 Telnet_Check_reachability 这个功能。我认为这可能是进程以字节为单位。需要转换为str。你知道如何转换吗?我尝试使用 stdout=stdout.decode("UTF-8"),但仍然无法正常工作,并且出现错误:UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa8 in position 22:
【解决方案2】:

使用 value=value.decode('utf8') 后,它现在可以工作了。

value = tn.read_until(b"Router#")
    #print value
    tn.close()
    time.sleep(1)

    info = "2001"

    #value=str(value)
    value=value.decode('utf8')
    matchObj = re.match(r'.*'+ info + '(.*)\n',value, re.M|re.DOTALL)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-21
    • 2021-02-08
    • 1970-01-01
    • 2020-08-26
    • 2016-10-09
    • 1970-01-01
    • 1970-01-01
    • 2016-06-03
    相关资源
    最近更新 更多