【问题标题】:While running a Python script, I'm getting an error运行 Python 脚本时,出现错误
【发布时间】:2019-08-23 11:40:44
【问题描述】:

在运行下面的 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 的身份运行它。

标签: python python-2.x telnet


【解决方案1】:

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

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

Telnet.write(缓冲区) 将 byte string 写入套接字,将任何 IAC 字符加倍。如果连接被阻止,这可能会阻止。如果 连接已关闭。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-17
    • 2020-08-02
    • 2022-01-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多