运行Python脚本时,出现错误

时间:2019-04-02 03:05:21

标签: 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.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

请帮助我解决这个问题。

1 个答案:

答案 0 :(得分:0)

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

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

  

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

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

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