运行Python脚本时,我';我犯了一个错误

运行Python脚本时,我';我犯了一个错误,python,python-2.x,telnet,Python,Python 2.x,Telnet,运行下面的Python脚本时,我遇到一个错误: [root@localhost ~]# cat pythonR5script1 import getpass import sys import telnetlib HOST = "100.100.100.1" user = raw_input("Enter your telnet username: ") password = getpass.getpass() tn = telnetlib.Telnet(HOST) tn

运行下面的Python脚本时,我遇到一个错误:

 [root@localhost ~]# cat pythonR5script1
 import getpass
 import sys
 import telnetlib

 HOST = "100.100.100.1"
 user = raw_input("Enter your telnet username: ")
 password = getpass.getpass()

 tn = telnetlib.Telnet(HOST)

 tn.read_until("username: ")
 tn.write(user + "\r\n")
 if password:
    tn.read_until("Password: ")
    tn.write(password + "\r\n")

tn.write("enable\r\n")
tn.write("cisco\r\n")
tn.write("conf t\r\n")
tn.write("int loop 0\r\n")
tn.write("ip add 200.200.200.1 255.255.255.255\r\n")
tn.write("end\r\n")
tn.write("exit\r\n")


print tn.read_all()
这就是我得到的错误:

[root@localhost ~]# python pythonR5script1 
Enter your telnet username: alan
Password: 
Traceback (most recent call last):
  File "pythonR5script1", line 14, in <module>
tn.read_until("Password: ")
  File "/usr/local/lib/python2.7/telnetlib.py", line 294, in read_until
return self._read_until_with_poll(match, timeout)
  File "/usr/local/lib/python2.7/telnetlib.py", line 343, in _read_until_with_poll
return self.read_very_lazy()
  File "/usr/local/lib/python2.7/telnetlib.py", line 455, in read_very_lazy
raise EOFError, 'telnet connection closed'
EOFError: telnet connection closed
[root@localhost~]#pythonR5script1
输入您的telnet用户名:alan
密码:
回溯(最近一次呼叫最后一次):
文件“pythonR5script1”,第14行,在
tn.read_直到(“密码:”)
文件“/usr/local/lib/python2.7/telnetlib.py”,第294行,只读
返回self.\u读取\u直到\u与\u轮询(匹配,超时)
文件“/usr/local/lib/python2.7/telnetlib.py”,第343行,在带有轮询的
返回self.read_very_lazy()
文件“/usr/local/lib/python2.7/telnetlib.py”,第455行,以read\u very\u格式
提高EOR,“telnet连接已关闭”
EOR:telnet连接已关闭

请帮助我解决此问题。

您正在编写字符串,而write函数需要字节字符串。

Telnet.write(缓冲区) 将字节字符串写入套接字,将所有IAC字符加倍。如果连接被阻塞,这可能会阻塞。如果 连接已关闭

对发送到服务器的字符串执行encode()函数


tn.write('{}\r\n'.format(user).encode())
您正在写入字符串,而write函数需要字节字符串。

Telnet.write(缓冲区) 将字节字符串写入套接字,将所有IAC字符加倍。如果连接被阻塞,这可能会阻塞。如果 连接已关闭

对发送到服务器的字符串执行encode()函数


tn.write('{}\r\n'.format(user).encode())

您几乎肯定不应该以
root
身份运行它。您几乎肯定不应该以
root
身份运行它。