使用python远程登录cisco交换机

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19671936/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 14:19:16  来源:igfitidea点击:

Telnet cisco switch using python

pythoncisco

提问by deep

I am telnetting to a cisco switch via python script. The code goes as follows:

我正在通过 python 脚本远程登录到 cisco 交换机。代码如下:

#!/usr/bin/python
import getpass
import sys
import telnetlib

HOST = "10.203.4.1"
user = raw_input("Enter your remote account: ")
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("vt100\n")
tn.write("ls\n")
tn.write("exit\n")
print tn.read_all()

It just hangs up after running the script. How can I resolve this?

它只是在运行脚本后挂断。我该如何解决这个问题?

采纳答案by Sudipta Chatterjee

Here is a simpler solution:

这是一个更简单的解决方案:

import pexpect
import getpass

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

child = pexpect.spawn ('telnet '+HOST)
child.expect ('Username: ')
child.sendline (user)
child.expect ('Password: ')
child.sendline (password)
# If the hostname of the router is set to "deep"
# then the prompt now would be "deep>"
routerHostname = "deep" #example - can be different
child.expect (routerHostname+'>')
child.sendline ('enable')

Etc.

等等。

回答by Back2Basics

First of all please consider using something besides telnet. SSH is a great drop in replacement. Secondly to make this pythonic use a library called pexpect to do this very thing. The last line would use the command .interact() to gain control again.

首先,请考虑使用除 telnet 之外的其他东西。SSH 是一个很大的替代品。其次,让这个 pythonic 使用一个名为 pexpect 的库来做这件事。最后一行将使用命令 .interact() 再次获得控制权。

回答by Italo Rossi

You should look at Trigger: https://trigger.readthedocs.org/en/latest/

你应该看看触发器:https: //trigger.readthedocs.org/en/latest/

It's a automation toolkit to interact with network devices, like cisco routers/switches:

它是一个与网络设备交互的自动化工具包,例如 cisco 路由器/交换机:

from trigger.cmds import Commando

class ShowClock(Commando):
    """Execute 'show clock' on a list of Cisco devices."""
    vendors = ['cisco']
    commands = ['show clock']

if __name__ == '__main__':
    device_list = ['foo1-abc.net.aol.com', 'foo2-xyz.net.aol.com']
    showclock = ShowClock(devices=device_list)
    showclock.run() # Commando exposes this to start the event loop

    print '\nResults:'
    print showclock.results

Check the docs for more information: https://trigger.readthedocs.org/en/latest/

查看文档以获取更多信息:https: //trigger.readthedocs.org/en/latest/

回答by Aniruddh Kadam

Cisco Python Telnet Script for cisco router and switches best and simple script for telneting and configuring layer 3 devices.

用于 cisco 路由器和交换机的 Cisco Python Telnet 脚本是用于 telneting 和配置第 3 层设备的最佳和简单脚本。

import getpass
import sys
import telnetlib

HOST = "YOUR ROUTER IP ADDRESS"
user = raw_input("Enter your telnet username: ")
password = getpass.getpass()

tn = telnetlib.Telnet(HOST)

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


 tn.write("exit\n")

  print tn.read_all()

link for the code : Download the script here

代码链接: 在此处下载脚本

Steps:

脚步:

  1. An end device with installed python and connect the end device to router

  2. Configure telnet and username and password database

  3. Run python script

  1. 安装了python的终端设备并将终端设备连接到路由器

  2. 配置telnet和用户名密码数据库

  3. 运行python脚本

回答by binod gupta

I wrote a similar code and got similar error. Then I made the code vocal to know where I am making mistake. What I concluded is: "Using read_all() function is not a good idea all the time. It reads infinitely and brings impression like hung mode. Try replacing it with device prompt followed by a timer during reading. And try printing it to see if code captured the desired output"

我写了一个类似的代码并得到了类似的错误。然后我让代码发声以知道我在哪里犯了错误。我得出的结论是:“一直使用 read_all() 函数并不是一个好主意。它会无限读取并带来像挂起模式这样的印象。尝试在阅读期间将其替换为设备提示和计时器。并尝试打印它以查看是否代码捕获了所需的输出”

import telnetlib
import os
import sys

host = raw_input("Enter the VG IP : ")
user = "cisco"
password = "cisco"
#cmd = raw_input("Enter the command you want to feed : ")
cmd1 = "term len 0"
cmd = "show clock"
pingable = False

response = os.system("ping -c 2 " + host)
if response == 0:
    pingable = True
    print(host, "is Pingable", pingable)
else:
    print(host, "is un-Pingable", pingable)

if(pingable):
    tn = telnetlib.Telnet(host)
    banner = tn.read_until("Username:", 5)
    tn.write(user + "\n")
    print(banner)
    tn.read_until("Password:", 5)
    tn.write(password1 + "\n")
    prompt = tn.read_until("#")
    print("I am logged in\n\n")
    print(prompt)
    tn.write(cmd1 + b"\n")
    output1 = tn.read_until("#",5)
    print("my first cmd output is :", output1, "\n")
    tn.write(cmd + "\n")
    output1 = tn.read_until("#",5)
    print("My 2nd cmd is feeded here", output1)
    tn.write("show version\n")
    output1 = tn.read_until("more-- ",5)
    print("version info : ", output1)
    tn.write("exit\n")

else:
    print(host, "is unpingable")