cancel
Showing results for 
Search instead for 
Did you mean: 
cancel
6466
Views
21
Helpful
7
Replies

Python script to change/update hostname's of multiple Cisco devices.

Hi,

It will be very helpful if someone can help with a script (preferably Python) using which I can change/update the hostnames of multiple Cisco devices instead of doing it one by one manually.

I already have the hostname configured just need to update the hostname across 100s of Cisco devices to maintain the standards.

Please note, I am very new to automation and for now, I only know how to SSH into Cisco devices using Python+Netmiko.

 

Thank you

Shiv

3 Accepted Solutions

Accepted Solutions

balaji.bandi
Hall of Fame
Hall of Fame

Here is Pythion script easy to understand and simple to replace what you like to replace on the devices :

 

https://github.com/grelleum/youtube-network-automation

 

check the youtube, his series simple, in hours time you can do what you want.

 

 

 

BB

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

How to Ask The Cisco Community for Help

View solution in original post

Seb Rupik
VIP Alumni
VIP Alumni

Hi there,

Try the following:

#!/usr/bin/env python3
import getpass
import csv
import netmiko
import paramiko
from argparse import ArgumentParser


def main():
    parser = ArgumentParser(description='Arguments for running oneLiner.py')
    parser.add_argument('-c', '--csv', required=True, action='store', help='Location of CSV file')
    args = parser.parse_args()

    ssh_username = input("SSH username: ")
    ssh_password = getpass.getpass('SSH Password: ')

    with open(args.csv, "r") as file:
        reader = csv.DictReader(file)
        for device_row in reader:
            try:
                ssh_session = netmiko.ConnectHandler(device_type='cisco_ios', ip=device_row['device_ip'],
                                                     username=ssh_username, password=ssh_password)

                print("+++++ {0} +++++".format(device_row['device_ip']))
                commands = ["hostname {0}".format(device_row['new_hostname'])]
                ssh_session.enable()
                ssh_session.send_config_set(commands)
                ssh_session.send_command("wr mem")
                ssh_session.disconnect()

            except (netmiko.ssh_exception.NetMikoTimeoutException,
                    netmiko.ssh_exception.NetMikoAuthenticationException,
                    paramiko.ssh_exception.SSHException) as s_error:
                print(s_error)


if __name__ == "__main__":
    main()

You will need to feed it a csv file with the following format:

device_ip,new_hostname
192.168.1.1,new_host01 192.168.1.2,new_host02 192.168.1.3,new_host03
# python3 -c new_hostnames.csv

The script will prompt you for a username and password and will use those credentials for every device in the csv file.

 

cheers,

Seb.

 

View solution in original post

Hi There,

Thank you everyone for the help and pointers.

I completed the task using the script and prerequisite points mentioned below.

1. I ran Python on a Windows laptop.

2. Used a SwitchIPList.txt file.

3. I used the below script.

Task accomplished.

I have added a lot of separators, you can edit/remove them.

Below is the script that executed repetitive commands on multiple network nodes. I hope it helps.

from netmiko import ConnectHandler
from getpass import getpass
#import sys

#SSH to multpile devices
#create device template
with open("SwitchIPList.txt") as switches:
    for IP in switches:
        Switch = {
            "device_type": "cisco_ios",
            "ip": IP,
            "username": input("Username: "),
            "password": getpass(),
#            "username": "",
#            "password": "",
        }
        net_connect = ConnectHandler(**Switch)
############################## Connect to IP ##############################
        print("*"*90)
        print ("Connecting to " + IP)
        print("*"*90)
############################## show commands ##############################
        output = net_connect.send_command("show run | s aaa group|radius server")
        print(output)
        print("-"*72)
############################## Config radius server ##############################
        config_commands = ["radius server naca001.nac.com\n",
                            "address ipv4 10.200.0.1 auth-port 1812 acct-port 1813\n",
                            "automate-tester username GNSRADIUS idle-time 10\n",
                            "key YourPassword\n",
                            "!\n",
                            "radius server naca002.nac.com\n",
                            "address ipv4 10.200.0.2 auth-port 1812 acct-port 1813\n",
                            "automate-tester username GNSRADIUS idle-time 10\n",
                            "key YourPassword\n",
                            "!\n",
                                                        	]
        output = net_connect.send_config_set(config_commands)
        print(output)
        print("-"*72)
        output = net_connect.send_command("show run | s aaa group|radius server")
        print(output)
        print("-"*72)
############################## Test NAC ##############################
        print("+"*10,"Test to radius server naca001.nac.com - 10.200.0.1","+"*10)
        output = net_connect.send_command("test aaa group NAC-V2 test test legacy")
        print(output)
        print("-"*72)
        output = net_connect.send_command("wr")
        print(output)
        print("-"*72)
        print("="*27,"END OF SWITCH","="*27)
        
#Close the connection
net_connect.disconnect()

 

 

Thank you

Shiv

 

 

 
 

View solution in original post

7 Replies 7

Hi @inderdeeps, Thank you for your response. I am looking for something simple to understand.

balaji.bandi
Hall of Fame
Hall of Fame

Here is Pythion script easy to understand and simple to replace what you like to replace on the devices :

 

https://github.com/grelleum/youtube-network-automation

 

check the youtube, his series simple, in hours time you can do what you want.

 

 

 

BB

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

How to Ask The Cisco Community for Help

Hi @balaji.bandi, Thank you for your response.

I went through few initial videos. It seems simple and interesting. Let me go through all and see if I find the solution.

 

Thank you

Shiv 

if you see all 9 or 10 videos, you become python network programmer can do day to day task.

 

Good Luck.

 

BB

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

How to Ask The Cisco Community for Help

Seb Rupik
VIP Alumni
VIP Alumni

Hi there,

Try the following:

#!/usr/bin/env python3
import getpass
import csv
import netmiko
import paramiko
from argparse import ArgumentParser


def main():
    parser = ArgumentParser(description='Arguments for running oneLiner.py')
    parser.add_argument('-c', '--csv', required=True, action='store', help='Location of CSV file')
    args = parser.parse_args()

    ssh_username = input("SSH username: ")
    ssh_password = getpass.getpass('SSH Password: ')

    with open(args.csv, "r") as file:
        reader = csv.DictReader(file)
        for device_row in reader:
            try:
                ssh_session = netmiko.ConnectHandler(device_type='cisco_ios', ip=device_row['device_ip'],
                                                     username=ssh_username, password=ssh_password)

                print("+++++ {0} +++++".format(device_row['device_ip']))
                commands = ["hostname {0}".format(device_row['new_hostname'])]
                ssh_session.enable()
                ssh_session.send_config_set(commands)
                ssh_session.send_command("wr mem")
                ssh_session.disconnect()

            except (netmiko.ssh_exception.NetMikoTimeoutException,
                    netmiko.ssh_exception.NetMikoAuthenticationException,
                    paramiko.ssh_exception.SSHException) as s_error:
                print(s_error)


if __name__ == "__main__":
    main()

You will need to feed it a csv file with the following format:

device_ip,new_hostname
192.168.1.1,new_host01 192.168.1.2,new_host02 192.168.1.3,new_host03
# python3 -c new_hostnames.csv

The script will prompt you for a username and password and will use those credentials for every device in the csv file.

 

cheers,

Seb.

 

Hi There,

Thank you everyone for the help and pointers.

I completed the task using the script and prerequisite points mentioned below.

1. I ran Python on a Windows laptop.

2. Used a SwitchIPList.txt file.

3. I used the below script.

Task accomplished.

I have added a lot of separators, you can edit/remove them.

Below is the script that executed repetitive commands on multiple network nodes. I hope it helps.

from netmiko import ConnectHandler
from getpass import getpass
#import sys

#SSH to multpile devices
#create device template
with open("SwitchIPList.txt") as switches:
    for IP in switches:
        Switch = {
            "device_type": "cisco_ios",
            "ip": IP,
            "username": input("Username: "),
            "password": getpass(),
#            "username": "",
#            "password": "",
        }
        net_connect = ConnectHandler(**Switch)
############################## Connect to IP ##############################
        print("*"*90)
        print ("Connecting to " + IP)
        print("*"*90)
############################## show commands ##############################
        output = net_connect.send_command("show run | s aaa group|radius server")
        print(output)
        print("-"*72)
############################## Config radius server ##############################
        config_commands = ["radius server naca001.nac.com\n",
                            "address ipv4 10.200.0.1 auth-port 1812 acct-port 1813\n",
                            "automate-tester username GNSRADIUS idle-time 10\n",
                            "key YourPassword\n",
                            "!\n",
                            "radius server naca002.nac.com\n",
                            "address ipv4 10.200.0.2 auth-port 1812 acct-port 1813\n",
                            "automate-tester username GNSRADIUS idle-time 10\n",
                            "key YourPassword\n",
                            "!\n",
                                                        	]
        output = net_connect.send_config_set(config_commands)
        print(output)
        print("-"*72)
        output = net_connect.send_command("show run | s aaa group|radius server")
        print(output)
        print("-"*72)
############################## Test NAC ##############################
        print("+"*10,"Test to radius server naca001.nac.com - 10.200.0.1","+"*10)
        output = net_connect.send_command("test aaa group NAC-V2 test test legacy")
        print(output)
        print("-"*72)
        output = net_connect.send_command("wr")
        print(output)
        print("-"*72)
        print("="*27,"END OF SWITCH","="*27)
        
#Close the connection
net_connect.disconnect()

 

 

Thank you

Shiv