执行 Cisco Python 脚本时出现问题

问题描述 投票:0回答:2

运行我从 stackoverflow 获取的以下脚本来登录连接到控制台服务器的 Cisco 交换机,并发出“sh run”命令。

#!usr/bin/python
import getpass
import telnetlib

HOST = "10.252.128.81:3132"

user = input("Enter your username: ")
password = getpass.getpass()

tn = telnetlib.Telnet(HOST)

tn.read_until("login: ")
tn.write(user + "\n")

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

tn.write("show run\n")
tn.write("exit\n")

print(tn.read_all()) 

Python 新手,因此当我运行脚本时,我得到以下输出。

Enter your username: user1
Warning: Password input may be echoed.
Password: cisco123
Traceback (most recent call last):
  File "D:\Users\ted\workspace\Test\cisco.py", line 10, in <module>
    tn = telnetlib.Telnet(HOST)
  File "C:\Python34\lib\telnetlib.py", line 221, in __init__
    self.open(host, port, timeout)
  File "C:\Python34\lib\telnetlib.py", line 237, in open
    self.sock = socket.create_connection((host, port), timeout)
  File "C:\Python34\lib\socket.py", line 494, in create_connection
    for res in getaddrinfo(host, port, 0, SOCK_STREAM):
  File "C:\Python34\lib\socket.py", line 533, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno 11004] getaddrinfo failed

有什么想法吗?

python python-3.x cisco-ios
2个回答
0
投票

不严格回答您的问题,但根据您的目标,它可能会有所帮助。 我正在使用 PrettyGoodTerminal 编写 Cisco 路由器脚本,因为它为我管理连接,而 Python 部分更多的是关于发送命令和处理结果。对于简单的“sh run”,你也不需要 Pytonh,但看起来像这样:

result = Terminal.ExecCommand("sh run","#")
commandResult = result[0]
timedOut = result[1]
if not timedOut:
  ActionResult = commanResult
  ScriptSuccess = True

0
投票

您不能将

addr:port
表示法与
telnetlib
...
split()
冒号上的主机名和端口一起使用,那么它将起作用...

#!usr/bin/python
import getpass
import telnetlib

HOST = "10.252.128.81:3132"

user = input("Enter your username: ")
password = getpass.getpass()

################################################
# Answer: Split the addr and port
################################################
addr, port = HOST.split(':')
tn = telnetlib.Telnet(addr, port)

tn.read_until("login: ")
tn.write(user + "\n")

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

tn.write("show run\n")
tn.write("exit\n")

print(tn.read_all()) 
© www.soinside.com 2019 - 2024. All rights reserved.