pythonnetwork-programmingautomationcisconetmiko

Python | Netmiko | Auto ping


im beginner and i have tried for a lot

code :

conn = netmiko.ConnectHandler(ip='10.254.60.10', device_type='cisco_ios', 
                                username='user', password='P@ssw0rd')

print (conn.send_command('show interface Ethernet0/0 | i line|Des|Int'))

output like this

Ethernet0/0 is up, line protocol is up Description: CUSTOMER A
Internet address is 10.254.60.69/30

how to auto ping to IP PtP using conn.send_command() based on result of show interface command?

example ping to 10.254.60.70


Solution

  • You get text

    text = '''Ethernet0/0 is up, line protocol is up Description: CUSTOMER A
    Internet address is 10.254.60.70/30'''
    

    and you can get IP/MASK using string functions

    address = text.split(' ')[-1]
    print(address)  # 10.254.60.70/30
    

    and then you can use standard module ipaddress

    import ipaddress
    
    net = ipaddress.ip_interface(address)
    ip = str(net.network.broadcast_address)
    print( ip )   # 10.254.60.71 
    

    or not standard module netaddr

    import netaddr
    
    net = netaddr.IPNetwork(address)
    ip = str(net.broadcast)
    print( ip )   # 10.254.60.71 
    

    EDIT: Minimal working code

    text = '''Ethernet0/0 is up, line protocol is up Description: CUSTOMER A
    Internet address is 10.254.60.69/30'''
    
    address = text.split(' ')[-1]
    print(address)  # 10.254.60.69/30
    
    print('\n--- ipaddress ---\n')
    
    import ipaddress
    
    net = ipaddress.ip_interface(address)
    
    print('ip  :', net.ip )   # 10.254.60.69 
    print('ip+1:', net.ip+1 ) # 10.254.60.70
    print('ip-1:', net.ip-1 ) # 10.254.60.68
    
    #bip = net.network.broadcast_address
    bip = str(net.network.broadcast_address)
    print('bip :', bip )      # 10.254.60.71 
    
    print('\n--- netaddr ---\n')
    
    import netaddr
    
    net = netaddr.IPNetwork(address)
    
    print('ip  :', net.ip )   # 10.254.60.69 
    print('ip+1:', net.ip+1 ) # 10.254.60.70
    print('ip-1:', net.ip-1 ) # 10.254.60.68
    
    bip = net.broadcast
    #bip = str(net.broadcast)
    print('bip :', bip )      # 10.254.60.71 
    

    Result:

    10.254.60.69/30
    
    --- ipaddress ---
    
    ip  : 10.254.60.69
    ip+1: 10.254.60.70
    ip-1: 10.254.60.68
    bip : 10.254.60.71
    
    --- netaddr ---
    
    ip  : 10.254.60.69
    ip+1: 10.254.60.70
    ip-1: 10.254.60.68
    bip : 10.254.60.71