【问题标题】:Python - capture the output from a sh command, obtain IP address and run a pingPython - 捕获 sh 命令的输出,获取 IP 地址并运行 ping
【发布时间】:2017-06-18 23:13:24
【问题描述】:

下面是我的工作代码,用于在 Cisco 路由器上显示我的路由器 arp 表。

我手头有一个任务,需要我从“sh arp”命令的输出中读取特定值,并将其用作要在 Cisco 路由器上执行的另一个命令的输入。

路由器中的命令:

1- sh arp vrf 互联网 |公司 0835.71

2- ping vrf INTERNET 100.124.162.230**

我已经完成了第 1 步。我可以得到输出,但我需要 hep 来完成第 2 步,以捕获 IP“100.124.162.230 运行 ping 到它。

print("正在 Ping NMD....")

    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    ssh.connect("r-a" ,timeout = 10)
    chan = ssh.invoke_shell()
    time.sleep(.1)
    chan.send('sh arp vrf INTERNET | INC  0835.71 \n')
    time.sleep(20)


    #Print command output
    while chan.recv_ready():
            output = str(chan.recv(99999999))
            output.encode('utf-8')
            #print(type(output))
            #print("\n\n\nPrinting total output: {0}".format(output))

输出:

r-a>sh arp vrf 互联网 |公司 0835.71 互联网 100.124.162.230 74 0835.71ef.d0a1 ARPA GigabitEthernet0/0.901

2- 下一步是获取 IP 并对其运行 ping 请帮助。

我提取了我的 IP 地址,现在我想对提取的 IP 运行 ping,我如何在 python 中执行此操作。请帮忙..

r-a>sh arp vrf 互联网 |公司 0835 互联网 100.114.162.230 110 0835.71ef.d0a1 ARPA GigabitEthernet0/0.901 r-a.> ['100.114.162.230']

    ssh.connect("r-a" + name + ".us", username = 'cisco', password = '1234', timeout = 10)
    chan = ssh.invoke_shell()
    time.sleep(.1)
    chan.send('sh arp vrf INTERNET' + ' ' + '|'+ ' ' + 'inc 0835' '\n')
    time.sleep(2)
    chan.send('ping' + ' ' + 'ip' '\n' )      

    #Print command output
    while chan.recv_ready():
            output = str(chan.recv(99999999))
            output.encode('utf-8')
            print("\n\n\nPrinting total output: {0}".format(output))
    ip = re.findall(r'100.\d+\d+.\d+.\d',output)
    print(ip)

【问题讨论】:

  • 只是为了确保您显示的字符串是output.encode('utf-8')的结果?
  • 是的,我能够捕获 IP 并打印它。现在我需要找到一种方法来获取打印机并运行 ping 以查看它是否 ping。我已经更新了我正在提取的输出。

标签: python network-programming cisco-ios


【解决方案1】:

这样的事情可能会奏效,但如果你能够通过 ssh 访问它,我可能又错过了什么?:

_, stdout, _ = ssh.exec_command('hostname')
hostname = stdout.read()
ssh.close()
HOST_UP  = True if os.system("ping -c 1 " + hostname) is 0 else False

相关:

【讨论】:

  • 是的,我可以 ssh,一切正常,我是 python 新手,不知道如何从 arp 表中获取 IP 并对其运行 ping。
  • @zenki 你的问题比我最初想象的要复杂得多。我添加了一些使用较低级别的 ioctl 调用获取部分信息的方法的链接。
  • 我提取了我的 IP 地址,现在我想对提取的 IP 运行 ping,我如何在 python 中执行此操作。请帮忙......
猜你喜欢
  • 2014-03-01
  • 1970-01-01
  • 2015-06-19
  • 2017-08-31
  • 2018-03-11
  • 1970-01-01
  • 2015-07-01
  • 2014-03-03
  • 1970-01-01
相关资源
最近更新 更多