【问题标题】:Connection to a router does not open无法打开与路由器的连接
【发布时间】:2020-11-09 11:14:57
【问题描述】:

我尝试使用 Python 脚本通过 GNS3 连接到路由器 R1:

import getpass
import sys
import telnetlib

HOST = "192.168.1.1"
user = raw_input("Enter your remote account: ")
password = getpass.getpass()

tn = telnetlib.Telnet(HOST)

tn.read_until(b"Username: ")
tn.write(user + "\n")
if password:
    tn.read_until("Password: ")
    tn.write(password + "\n")

tn.write("enable\n")
tn.write("cisco\n")
tn.write("conf t\n")
tn.write("exit\n")
tn.write("exit\n")


print(tn.read_all().decode('ascii'))

但它仍然冻结,因为我认为它无法通过tn = telnetlib.Telnet(HOST) 线路连接到路由器

当我执行 ^C 时出现此错误:

admin ~/Desktop $ python3 test.py
Enter your remote account: david
Password: 
^CTraceback (most recent call last):
  File "test.py", line 9, in <module>
    tn = telnetlib.Telnet(HOST)
  File "/usr/local/Cellar/python/3.6.5_1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/telnetlib.py", line 218, in _init_
    self.open(host, port, timeout)
  File "/usr/local/Cellar/python/3.6.5_1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/telnetlib.py", line 234, in open
    self.sock = socket.create_connection((host, port), timeout)
  File "/usr/local/Cellar/python/3.6.5_1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/socket.py", line 713, in create_connection
    sock.connect(sa)
KeyboardInterrupt

从 R1 的终端连接到 telnet 工作正常

【问题讨论】:

  • 按^C 时的错误信息是标准的,与代码中的任何问题无关。是否可以在命令行中使用telnet 连接到路由器?
  • @Code-Apprentice 是的,效果很好
  • 不需要指定端口号吗?默认端口为 0,可能对此连接无效。
  • 会导致进一步问题(但不能解决您的当前问题)的一件事是您使用字符串而不是字节序列与 Telnet 通信。您需要将它们全部替换为字节序列!
  • @Vijay 我也这么认为(文档不清楚),但默认端口在内部被端口 23 替换。

标签: python telnet cisco telnetlib


【解决方案1】:

试试这个代码:

import getpass
import sys
import telnetlib

HOST = "192.168.1.1"
PORT = 23

user = raw_input("Enter your remote account: ")
password = getpass.getpass()

tn = telnetlib.Telnet(HOST, PORT)

tn.read_until(b"Username: ")
tn.write(bytes(user + "\n", 'utf-8'))
if password:
    tn.read_until(b"Password: ")
    tn.write(bytes(password + "\n", 'utf-8'))

commands="enable\n cisco\n conf t\n exit\n exit\n"
tn.write(commands.encode())

print(tn.read_all())

如果您正确配置了路由器,此代码将起作用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-31
    • 2012-11-12
    • 1970-01-01
    • 2015-01-23
    • 2011-12-08
    相关资源
    最近更新 更多