简体   繁体   中英

Python2 to python3 lists and bytes vs strings

I have a list of IP addresses I telnet to and gather data from. I put this data into two variables. I then want to print the data from the variables into a HTML table. It worked in Python 2 but doesn't in Python 3. It is giving me the following error: Can't convert 'bytes' object to str implicitly . I see other people giving explanations to the byte code vs string code but what about lists? Please help if you can.

#!/usr/bin/python3

import cgi, cgitb
import telnetlib
import re
import socket

user            = 'usr'
password        = 'pwd'

print ("Content-type:text/html\r\n\r\n")
print ("<html>")
print ("<head>")
print ("<title>Locating IP Addresses</title>")
print ("<link href=\"/styles/main.css\" type=\"text/css\" rel=\"stylesheet\" >")
print ("</head>")
print ("<body>")

for count in ["10.1.1.4", "10.1.1.3", "10.1.1.2"]:
    server = (count)
    try:
        tn = telnetlib.Telnet(server)
        tn.read_until(b"ogin")
        tn.write(user.encode('ascii') + b"\r\n")
        tn.read_until(b"assword")
        tn.write(password.encode('ascii') + b"\r\n")
        tn.write(b"environment no more\r\n")
        tn.write(b"configure\r\n")
        tn.write(b"router\r\n")
        tn.write(b"info\r\n")
        tn.write(b"logout\r\n")
        output = (tn.read_all())
        interfaces = (re.findall(b'interface\s\"(.+)\"', output))
        ipaddr = (re.findall(b'address\s(.+)/', output))
        print ("<table>")
        print ("<tr>")
        print ("<th class=\"bld\">%s</th>" % (server))
        print ("</tr>")
        for i,j in zip(interfaces, ipaddr):
            print ("<tr>")
            print (("<td class=\"sn\">"+j+"</td>" "<td class=\"prt\">"+i+"</td>"))

        except socket.error:
            print ("communication error with " + server)

print ("</body>")
print ("</html>")

When you use bytes in a regex, the results will also be bytes, in this case that means interfaces and ipaddr will be lists of bytes.

Later you try to concatenate these results with strings using the + operator, which doesn't allow to mix bytes and str .

Try this instead:

print("<td class=\"sn\">"+j.decode()+"</td><td class=\"prt\">"+i.decode()+"</td>")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM