在运行Python脚本时,我遇到了错误

问题描述 投票:1回答:1

在下面运行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

请帮我解决这个问题。

python python-2.x telnet
1个回答
0
投票

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

https://docs.python.org/3/library/telnetlib.html?highlight=telnetlib#telnetlib.Telnet.write

Telnet.write(buffer)将一个字节字符串写入套接字,使任何IAC字符加倍。如果连接被阻止,这可能会阻止。如果连接关闭,可能会引发OSError。

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

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

© www.soinside.com 2019 - 2024. All rights reserved.