Question

With the below code I fetch the IP address from a text file which contains list of IP addresses. Then SSH into Cisco Router to make changes that is common to all the devices. This time however I have to make changes that are variable in nature.

Example:

I have to fetch the ip address (10.120.15.1) and SSH into the device and apply the following command

"access-list 150 permit ip 10.120.15.0 0.0.0.255 host 10.100.100.1"

The IP address is already contained in the variable "line" and I have to split the last octet and change it from "1" to "0" and then insert to the access list.

Please share your inputs.

import paramiko
import sys
import os
import time
import cmd

buff = ''
resp = ''

with open('Address.txt', 'r') as f:
    for line in f:
        line = line.strip()
        dssh = paramiko.SSHClient()
        dssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        dssh.connect(line, username='cisco', password='cisco')
        chan = dssh.invoke_shell()
        chan.send('conf t\n')
        time.sleep(1)
        resp = chan.recv(9999)
        chan.send('access-list 150 permit ip X.X.X.X 0.0.0.255 host 10.100.100.1\n exit\n')
        time.sleep(1)
        resp = chan.recv(9999) 
 dssh.close()
Was it helpful?

Solution

You can use the netaddr Python package.

Example:

>>> n = IPNetwork('10.120.15.1/24')
>>> list(n)[0:3]
[IPAddress('10.120.15.0'), IPAddress('10.120.15.1'), IPAddress('10.120.15.2')]
>>> IPNetwork('10.120.15.1/24').network
IPAddress('10.120.15.0')
>>> str(IPNetwork('10.120.15.1/24').network)
'10.120.15.0'

As for your script, you should be able to perform all of the access list modifications in the same SSH session, rather than one SSH session per address line.

I also suspect that you have inverted the netmask in your access-list command — it should probably be 255.255.255.0 rather than 0.0.0.255 (see examples).

Furthermore, I see that you are generating many access rules of the same form. That will be difficult to manage. Instead, you should write one access rule that references a network object group. You should only use your script to add/remove members of the group.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top