python - 与路由器的连接打不开

标签 python telnet cisco telnetlib

我尝试使用 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 工作正常

最佳答案

试试这段代码:

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())

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

关于python - 与路由器的连接打不开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62991390/

相关文章:

Java netty客户端无法向服务器发送消息,但telnet到服务器正常

c# - Cisco TSP - 在 C# 中从 32 位工具迁移到 64 位

python - 编码字符串

python - 用于保存和查询坐标的高性能 python 数据结构

ssh - Telnet 相对于 SSH 的优势?

http - 如何通过 telnet POST REQUEST 保存文件?

python - Paramiko 上的 exec_command 和使用 invoke_shell() 发送有什么区别?

php - 使用 SNMP WALK 获取一个端口上的 MAC 地址列表

python - 文本中低位单词的数量。 Python

python - 预期关键数据类型不匹配 : S actual: L Dynamodb insert error with boto3