cancel
Showing results for 
Search instead for 
Did you mean: 
cancel
2544
Views
5
Helpful
8
Replies

ping doesn't work in python script running on Nexus

Hello,

 

I try to create a python script and schedule it to run every 5 minutes on Nexus switches.

One of the checks, it will be the output of a simple ping.

 

I have tried different ways to execute a ping from python script but nothing works.

When i run the script from my laptop (Windows 10), it executes the ping command without any issue.

 

Example:

 

import os

hostnames = [
    '192.168.1.1'
]

for hostname in hostnames:
    response = os.system('ping ' + hostname)
    if response == 0:
        print(hostname, 'is up')
    else:
        print(hostname, 'is down')


 

Nexus# >>> os.system('ping 192.168.1.1')
system(ping 192.168.1.1): rejected!
-1
Nexus# >>>

 

Could you please let me know if there is any way to run a ping on Nexus using python?

 

Thank you

8 Replies 8

balaji.bandi
Hall of Fame
Hall of Fame

how are you running this script in nexus device ?

BB

***** Rate All Helpful Responses *****

How to Ask The Cisco Community for Help

I have tried to execute the script command by command in python shell or with the source command from Nexus (e.g. source version.py)

@anousakisioannis try this example --> https://developer.cisco.com/docs/nx-os/#!troubleshooting/ping

Please mark this as helpful or solution accepted to help others
Connect with me https://bigevilbeard.github.io

I copied the script as it is in the link and i get the below errors

 

 

Nexus# source test2.py
ERROR: ld.so: object '/isan/lib/libsandbox.so' from LD_PRELOAD cannot be preloaded: ignored.
no sandbox
disable sandbox before enabled
no sandbox
Bareword found where operator expected at (eval 1) line 6, near "'172.31.219.60'
count"
(Missing operator before count?)
Bareword found where operator expected at (eval 1) line 7, near "'4'
vrf"
(Missing operator before vrf?)
Bareword found where operator expected at (eval 1) line 10, near "'management'


def"
(Missing operator before def?)
String found where operator expected at (eval 1) line 13, near """"
Checks if the host is reachable
""
(Might be a runaway multi-line "" string starting on line 11)
(Missing operator before "
Checks if the host is reachable
"?)
String found where operator expected at (eval 1) line 13, near ""
Checks if the host is reachable
""""
(Missing operator before ""?)
Bareword found where operator expected at (eval 1) line 14, near """
try"
(Missing operator before try?)
Bareword found where operator expected at (eval 1) line 24, near ")
except"
(Missing operator before except?)

@anousakisioannis you can also try Using the CLI Command APIs

https://www.cisco.com/c/en/us/td/docs/switches/datacenter/nexus9000/sw/7-x/programmability/guide/b_Cisco_Nexus_9000_Series_NX-OS_Programmability_Guide_7x/Python_API.html#concept_6414B967674E46A5B13EC9CF61C88880

Please mark this as helpful or solution accepted to help others
Connect with me https://bigevilbeard.github.io

I have tried cli and clip which both are working but i cannot do error handling. I have tried the try-except and the below but nothing worked

 

response = clip('ping 192.168.1.1')
if response == 0:
    print(hostname, 'is up')
else:
    print(hostname, 'is down')

 

I think that the error handling isn't working because the ping command is running on NexusOS and it's not a native python command.

Hello @anousakisioannis,

I ran through the ping script here and was able to get it to run successfully.

Note that I didn't want to step on anyone's script, so I used two underscores when I named it: test__ping.py

sandbox-nxos-1.cisco# show run | in bash
feature bash-shell
sandbox-nxos-1.cisco# run bash
bash-4.3$ sudo su
bash-4.3# 
bash-4.3# vi /isan/python/scripts/cisco/test__ping.py from .nxcli import NXCLI import traceback # Fill the details to troubleshoot using ping host = '172.31.219.60' count = '4' vrf = 'management' def check_ping_ops(): """ Checks if the host is reachable """ try: interface = NXCLI('ping %s count %s vrf %s' % (host, count, vrf)) return True except: return False if __name__=="__main__": try: check_ping_ops() except Exception,e: traceback.print_exc() ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ "/isan/python/scripts/cisco/test__ping.py" [New] 25L, 470C written bash-4.3#

Here's the running script:

bash-4.3# /isan/bin/python -m cisco.test__ping
PING 172.31.219.60 (172.31.219.60): 56 data bytes
Request 0 timed out
Request 1 timed out
Request 2 timed out
Request 3 timed out

--- 172.31.219.60 ping statistics ---
4 packets transmitted, 0 packets received, 100.00% packet loss

bash-4.3# 

I then modified the script so that a successful ping could also be demonstrated:

bash-4.3# cat /isan/python/scripts/cisco/test__ping.py 
from .nxcli import NXCLI
import traceback

# Fill the details to troubleshoot using ping
count = '4'
vrf = 'management'

hostinfo = [
    ('172.31.219.60', vrf),
    ('192.168.2.1', 'default')
]


def check_ping_ops(host, vrf):
    """
    Checks if the host is reachable
    """
    try:
        interface = NXCLI('ping %s count %s vrf %s' % (host, count, vrf))
        return True
    except:
        return False


if __name__=="__main__":
    try:
        for info in hostinfo:
            host, vrf = info[0], info[1]
            check_ping_ops(host, vrf)
    except Exception,e:
        traceback.print_exc()

Here's the output:

bash-4.3# /isan/bin/python -m cisco.test__ping
PING 172.31.219.60 (172.31.219.60): 56 data bytes
Request 0 timed out
Request 1 timed out
Request 2 timed out
Request 3 timed out

--- 172.31.219.60 ping statistics ---
4 packets transmitted, 0 packets received, 100.00% packet loss

PING 192.168.2.1 (192.168.2.1): 56 data bytes
64 bytes from 192.168.2.1: icmp_seq=0 ttl=255 time=0.437 ms
64 bytes from 192.168.2.1: icmp_seq=1 ttl=255 time=0.366 ms
64 bytes from 192.168.2.1: icmp_seq=2 ttl=255 time=0.291 ms
64 bytes from 192.168.2.1: icmp_seq=3 ttl=255 time=0.276 ms

--- 192.168.2.1 ping statistics ---
4 packets transmitted, 4 packets received, 0.00% packet loss
round-trip min/avg/max = 0.276/0.342/0.437 ms

bash-4.3# 

fjm

@ittybittypacket

fracjackmac
Level 1
Level 1

I made additional modifications to the script to hide the ping command output and provide an "up" or "down" indication.

bash-4.3# cat /isan/python/scripts/cisco/test__ping.py 
from .nxcli import NXCLI
import traceback

# Fill the details to troubleshoot using ping
count = '4'
vrf = 'management'

hostinfo = [
    ('172.31.219.60', vrf),
    ('192.168.2.1', 'default')
]


def check_ping_ops(host, vrf, do_print=False):
    """
    Checks if the host is reachable
    """
    try:
        interface = NXCLI('ping %s count %s vrf %s' % (host, count, vrf), do_print)
        for feedback in interface.get_output():
            if '100.00% packet loss' in feedback:
                return False
        return True
    except:
        return False


if __name__=="__main__":
    try:
        for info in hostinfo:
            host, vrf = info[0], info[1]
            response = check_ping_ops(host, vrf)
            if response:
                print "\nHost {} is currently up / alive\n".format(host)
            else:
                print "\nHost {} is currently down / unreachable\n".format(host)
    except Exception,e:
        traceback.print_exc()
bash-4.3# 

bash-4.3# /isan/bin/python -m cisco.test__ping

Host 172.31.219.60 is currently down / unreachable


Host 192.168.2.1 is currently up / alive

bash-4.3# 

Note that I used the phrase "100.00% packet loss" as the key to determine whether or not a test was considered successful.

 

fjm

@ittybittypacket