2013-04-17 63 views
0

我有一個IP地址列表,我telnet到並從中收集數據。我把這些數據分成兩個變量。然後我想要將變量中的數據打印到HTML表格中。它在Python 2中工作,但不在Python 3中。它給了我以下錯誤:Can't convert 'bytes' object to str implicitly。我看到其他人給出瞭解釋字節碼vs字符串代碼,但列表呢?如果可以的話請幫忙。Python2到python3列表和字節與字符串

#!/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>") 
+0

我或許可以幫忙,但是你可以張貼完整的錯誤信息,即包括行號?我看不到錯誤發生在哪裏。 – refi64

回答

0

當你在一個正則表達式使用字節,其結果也將是字節,在這種情況下,這意味着interfacesipaddr將字節的名單。

稍後嘗試將這些結果與使用+運算符的字符串連接起來,該運算符不允許混合使用bytesstr

試試這個:

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

你真棒我的朋友。像魅力一樣工作。 – Philter