Network Automation using Python – Part IV – SSH to Cisco Device

Continuing our Networking Automation using Python blog series, here is the Part 4.

We had explained the ways to take a Telnet session to the Switches in our previous posts. Now here we are explaining the steps to SSH to Cisco switch using Python script and to configure IP on vlan interface. IP configuration is an example here, once you have SSH’ed to the switch, you can perform any other configuration as per your requirement, by just modifying the script a bit. Please read part 1 and part 2 to get an idea about how to install python and run your first program.

We are using netmiko module for taking SSH session of device.

What is Netmiko ?

Read more

Netmiko is open-source Python library that simplifies SSH management to network devices. This is a common and easy to use library as netmiko supporting multi vendor devices.You can read more about netmiko from here . Following are the some of the vendor devices supported by Netmiko .

——————- advertisements ——————-

———————————————————-

Arista vEOS
Cisco ASA
Cisco IOS
Cisco IOS-XE
Cisco IOS-XR
Cisco NX-OS
Cisco SG300
HP Comware7
HP ProCurve
Juniper Junos
Linux

How to install Netmiko

Netmiko package not available by default. You should have netmiko library installed on your machine .Following are the steps to download and install netmiko in Python 3.6

Step 1. Working internet connection and Python 3.6 installed on machine

Step 2. On command prompt, type following command, this will automatically fetch netmiko from internet and install on your machine

“python -m pip install netmiko”

——————- advertisements ——————-

———————————————————-

Following are the steps to start with netmiko on your script

Import netmiko to your Script

Use the following command to import netmiko package to your script

from netmiko import ConnectHandler

Create Device template 

We have to create device template using python dictionary data type.

cisco_swicth = {
‘device_type’: ‘cisco_ios’,
‘ip’: ‘10.10.10.10’,
‘username’: ‘admin’,
‘password’: ‘Beginnersforum’,
‘port’ : 22,
‘secret’: ‘enablepassword’# optional, replace with your enable password ”
}

——————- advertisements ——————-

———————————————————-

where,

cisco_switch ->This is name of template, you can give any name like cisco_2960,juniper_sw etc

‘device_type’ -> Here we are specifying the type of device we are taking ssh,

secret -> Here we are giving the enable password

Port and secret are optional here and the default value for port is 22.

Establish an SSH connection to the device

We are estabishing SSH connection to device by passing the above defined template

ssh_connect = ConnectHandler (**cisco_switch)

Run Show command 

Here the ‘show ip int brief” command will execute on remote device and output will store to ‘result” variable. We can print “result” to see the output on window

result = net_connect.send_command(show ip int brief) print(result)

——————- advertisements ——————-

———————————————————-

Sample output :

Interface IP-Address OK? Method Status Protocol
FastEthernet0 unassigned YES unset down down
FastEthernet1 unassigned YES unset down down
FastEthernet2 10.10.10.10 YES manual up up
Vlan1 unassigned YES unset down down

Complete Script – Download

You can download script (to SSH to a device and add IP address to vlan 10) from here. Please change the file extension from .txt to .py for executing directly.

Also, keeping a copy here in this post below.

 

from netmiko import ConnectHandler
import getpass
import sys

#create device template

cisco_switch = {
‘device_type’: ‘cisco_ios’,
‘ip’: ‘192.168.43.10’,
‘username’: ‘username’,
‘password’: ‘password’,
‘secret’:’password’
}

#Getting the user credential

print (“Script for SSH to device, Please enter your credential”)
device[‘username’]=input(“User name “)
device[‘password’]=getpass.getpass()
device[‘secret’]=input(“Enter enable password”)

#Establishing SSH connection
ssh_connect = ConnectHandler(**device)

#changing to enable mode
ssh_connect.enable()
ssh_connect.send_command(‘config t’)
ssh_connect.send_command(‘int vlan 10’)
ssh_connect.send_command(‘ip add 10.10.10.1 255.255.255.0)
ssh_connect.send_command(‘end’)
ssh_connect.send_command(‘write’)
ssh_connect.disconnect()

Hope you enjoyed reading. You can read more posts on Network automation using Python here. Please use the comments section for any queries/suggestions .

Network Automation using Python – Part II – Telnet to a Switch and IP configuration

This is the 2nd post from my Networking Automation using Python blog series.

As part of network automation, the first thing is accessing (Telnet -ing) a switch. Here is a simple program explaining step by step way to access Cisco switch using telnet and to configure IP address on Vlan interface – all using Python.

Please check out our first post Network Automation using Python – Part I for getting started with Python. We have explained the basics of Python and the installation procedure in the previous post.

“telnetlib” module

Read more

“telnetlib” is the name of module which is supporting to take the telnet of device. This will be automatically installed as part of your python installation

->Import telnet library

The first step is to import telnet library to our script , use the following command

“import telnetlib”

->Connecting a Host

To connect a device using telnetlib, use following command.

tn=telnetlib.Telnet(HOST)

——————- advertisements ——————-

———————————————————-

Where HOST is the variable which is having the IP address of device and “tn” is the           variable name which is creating virtual telnet link with your device. It could be any name as you wish ( like telnet or tnet) .You should use same name for the rest of the             operation on the device.

-> Writing  command to to Host

tn.write(“config t”)

The write() function using to deliver command to device. The above example will write       “config t”  command on the device telnet prompt.

-> Reading output from host

output=tn.read_all()

read_all() function will read the output of command from device and store in to the variable output

That concludes the basics for initiating a telnet session to the switch.

Following are the step by step guidelines to access the switch and then configure the IP on the switch. The steps explained below is based on 2.6 version for easy understanding. I have attached version 3.6 and 2.6 script also as there are changes in the script. The main difference in 3.6 as we need to convert all values in to ASCII before sending to device.

Step 1. Importing the required modules

import telnetlib

import getpass

import time

“getpass” is the module to read the password without printing on screen

“time” will be using to control the flow of program by pausing script certain duration

——————- advertisements ——————-

———————————————————-

Step 2. Initialise the Host Variable

The “Host” variable holding the IP address of Device . We can assign the IP address as follows. Please understa

HOST=”192.168.43.10″

Step 3. Read the user name and password

user = raw_input(“Enter your telnet username: “)
password = getpass.getpass()

raw_input() is an in built function used to read data giving by user and assigning to a variable. Here it will display “Enter your telnet username” on the screen and read the username provided by user and assign to variable called user. After executing those lines, we will have username on “user” variable and password on “password” variable.

Step 4. Connect to device and supply username and password

tn = telnetlib.Telnet(HOST)

tn.read_until(“Username: “)

tn.write(user + “\n”)

if password:

tn.read_until(“Password: “)

tn.write(password + “\n”)

tn = telnetlib.Telnet(Host)    // This command will initiate a telnet session to the given IP address on background .

tn.read_until(b”Username: “)    // This will be used to read output from device until it is asking for ‘Username’

tn.write(user + “\n”)   // This will supply the username to the telnet console followed by enter key. “\n” using to provide enter key.

——————- advertisements ——————-

———————————————————-

Step 5. Configure the device

In this step, we will be delivering configuration command to device one by one

tn.write(“enable\n”)    // changing to enable mode
tn.write(“cisco\n”)      // providing enable password
tn.write(“conf t\n”)     //moving to configuration mode
tn.write(“int vlan 10 \n”)   // changing to vlan 10 interface
tn.write(“ip address 1.1.1.1 255.255.255.255\n”)  // Assigning the IP address
tn.write(“end\n”)    //ending the configuration
tn.write(“exit\n”)

We have delivered all commands using write() function. You can use same write function to deliver the command as per your requirement. Save and Execute the script using RUN . Please refer part 1 if you don’d know how to write and execute script.

Script download

You can download the script for version 2.6, here

You can download the script for version 3.6, here

 

So, that’s it. Hope this helped you. You can read more posts on Network automation using Python here. Please use the comments section for your queries/comments.

 

Network Automation using Python – Part I – Python basics

We are starting with series of posts which will help you to automate your networking tasks using Python. This is a step by step guide which will show how to install Python and start your first program. You do not require any programming skill to start with automation. Please keep watching  on upcoming posts to understand better.

What is Python

Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language. It was created by Guido van Rossum during 1985- 1990. Like Perl, Python source code is also available under the GNU General Public License (GPL). This tutorial gives understanding how to install python one Windows machine and make it ready for Network Automation programming. Here in this post I will be covering only essential parts to start with Python so that we can continue with the network automation things in the coming posts. Please follow https://www.tutorialspoint.com/python/index.htm for more on basic/advanced python training.

Read more

Download Python

Download python from following link. You can either download 2.7 version or latest 3.6 version.Here we are showing 3.6 version since this is the latest and our all automation scripts are based on 3.6 version.

https://www.python.org/downloads/

Install Python.

Double click on the downloaded exe file and proceed with next until it gets installed.Leave all values default.

——————- advertisements ——————-

———————————————————-

Accessing Python.

Once it is installed, it will be available in  program list.

Click on Start-All Programs-Python 3.6  and click on IDLE .IDLE is the name of IDE for Python scripting .

Writing your first Program:

Once you have clicked IDLE, you will be available with following window.

To start with new program , click file -> New file. This will open new window where you can start coding.Here we will write a program to print Hello World . You can directly start coding from first line on wards as  python does not require any ‘main’ or ‘initialization’ statements for simple programs.

——————- advertisements ——————-

———————————————————-

Save the program

Click file and Save to save the program . The program will be saving with .py extension

Run the program.

Python does not require any compilation before running program as python is an interpreter program. To run the program , Select Run and click on Run Module

The result of the program will available on the first window. (Shell window)

——————- advertisements ——————-

———————————————————-

Accessing program from command line.

You can use following method to run the script which is created earlier or given by someone else. To run the program from command line, open CMD and navigate to the folder where your script has been saved .Type python and after that script file name on CMD. This will run the script and provide the out put on command prompt.

Hope you got the idea how to install Python and run your first program. Please click here for more posts from this series. Please use the comments section in case if you have any queries.

 

Juniper SRX Firewall Initial Configuration

Juniper SRX is the next generation firewall designed to provides high-speed, highly effective security services—even with multiple services enabled. The firewall released with a vast range of integrated security features suitable for securing medium to large scale enterprise Data Centers. Juniper has Virtual version vSRX focusing on security of cloud infrastructure.

The following steps describe the basic configuration settings of Juniper SRX Firewall.

We will be focusing on interface configuration, zone configuration and policy configuration

Following are the topics discussing over here.

Read more

1. Initialising SRX Firewall

2. Login to the firewall using console or GUI.

3. Configuring basic settings.

4. Configure interfaces.

5. Configure Zones and zone properties.

6. Configure firewall policies.


1. Initialising SRX Firewall and Login to the firewall

  • Unpack and power on the device. 
  • Plug one end of the CAT-5e (Ethernet cable) supplied with your firewall into the RJ-45 to DB-9 serial port adapter supplied with your firewall
  • Plug the RJ-45 to DB-9 serial port adapter into the serial port on the PC
  • Connect the other end of the Ethernet cable to the console port on the services gateway.
  • Open Hyper terminal and select COM1 with following settings

Port Settings Value

Bits per second : 9600

Data bits  :       8

Parity : None

Stop bits  :       1

Flow control : None

  • Log in as the user root. No password is required at initial connection, but you must assign a root password before committing any configuration settings
 

2. Configuring basic settings

Start the CLI

root# cli

Enter configuration mode:

[email protected]>configure

[edit]

Set root password
[email protected]set system root-authentication plain-text-password

New password: password

Retype new password: password

Set admin password

[edit]

[email protected]set system login user admin class super-user authentication plain-text-password

Set System host name

[edit]

root# set system hostname

 

Set DNS Servers

[edit]

root# set system name-server 8.8.8.8

[edit]

root# set system name-server 8.8.4.4

Commit the configuration and login with admin user. 

[edit]

3. Configure interfaces

We will use the following scenario to configure interfaces and zones.

Assign IP address for untrust interface

[edit]

root#set interface ge-0/0/0 unit 0 family inet address 192.168.1.1/24

Assign IP address for trust interface

[edit]

root#set interface ge-0/0/1 unit 0 family inet address 10.10.10.1/24

Configure default route

[edit]

[email protected]set routing-options static route 0.0.0.0/0 next-hop gateway

4. Configure Zones
Create untrust zone and assign interface 
[edit]
root# set security zones security-zone untrust interfaces ge-0/0/0.0
Create trust zone and assign interface
[edit]
root# set security zones security-zone trust interfaces ge-0/0/1.0

Enable ssh and https for firewall management on trust interface

[edit]

root# set system services ssh

[edit]

root# set security zones security-zone trust host-inbound-traffic system-services ssh

[edit]

root# set security zones security-zone trust host-inbound-traffic system-services http

[edit]

root# set system services web-management https system-generated-certificate

[edit]

root# set security zones security-zone trust host-inbound-traffic system-services https

 

5. Configure Firewall policy

Create a firewall policy to enable all the traffic from trust zone to internet.

[edit]

[email protected]set security policies from-zone trust to-zone untrust policy policy-name match source-address any 

destination-address any application any

[email protected]set security policies from-zone trust to-zone untrust policy policy-name then permit

Commit the configuration to active on the gateway.

[edit]

[email protected]commit

commitcomplete

 That’s it..! You are done with the initial configuration of a Juniper SRX firewall this system and is ready for production. Please watch this space for more posts on advanced configurations.
You may find more posts on firewall here.

Palo Alto Firewall Packet Flow

The following topics describe the basic packet processing in Palo Alto firewall. Focusing beginners who are finding difficulty to understand packet flow process in Palo Alto firewall, we have tried to simplify the steps as possible.

Let’s see what happens if a new packet comes to Palo Alto firewall in the following flow-chart.

Read more

——————————- Post continues below ——————————-

 

——————————- Post continues below ——————————-

 

 

Hope this helped you in understanding the packet flow. Please feel free to comment if you have any suggestions/questions.

You may find more posts on firewall here.

Brocade SAN switch zoning via CLI

We had discussed zoning in Cisco switch recently, in one of our posts. Now we will discuss the same on a Brocade switch via CLI. As we already discussed, the 3 components (zones, aliases and zoneset) remains the core here also. For reading bit more on this, you may read the previous post.

Now let’s directly come in to the commands for various steps.

Read more

We have the new HBA connected to the switch, we can ensure the successful connectivity by running switchshow command. This will show all the ports and the connected device WWNs, you can check the port number if you are aware of, or by finding the WWN (you may do a grep for the WWN).

Else if you are not aware of the switch and port on fabric on which the HBA is attached to, you may run nodefind. nodefind 10:xx:xx:xx:xx:xx:xx:01  will list the port details.

 

 

Now we can create the alias for the HBA (BForum_HBA1) and the storage port (VNX_SPA3). Below are the commands,

alicreate “BForum_HBA1″,”10:xx:xx:xx:xx:xx:xx:01”
alicreate “VXN_SPA3″,”50:06:xx:xx:xx:xx:xx:02”

For adding a WWN to an existing alias (adding a WWN – 10:xx:xx:xx:xx:xx:xx:02 to the alias BForum_HBA2 for example) you may run,

aliadd “BForum_HBA2″,”10:xx:xx:xx:xx:xx:xx:02”

Now we will be creating the zone for the HBA and storage port,

zonecreate “BForum_HBA1_VNX_SPA3″,”BForum_HBA1;VNX_SPA3”

We can add an alias to an existing zone by running the zoneadd command in similar way as we used aliadd command.

We can create zone config with the below command. This will add the zone to the cfg too..

cfgcreate “BForum_SAN1_CFG”,”BForum_HBA1_VNX_SPA3″

 

 

we should use the cfgadd command to add a new zone to an existing cfg as shown below,

cfgadd “BForum_SAN1_CFG”,”BForum_HBA1_VNX_SPB2

Thus we have the zones created and added to the (existing/new) config. Now we should save the config to memory to ensure this will be loaded in the next reboot of the switch also. The cfgsave command will do it for us.

We can now enable the zone config to make it in effect.

cfgenable BForum_SAN1_CFG

Yes we are all set. The server and storage now should be able to communicate. Some other useful commands are,

cfgshow BForum_SAN1_CFG           #Shows the config BForum_SAN1_CFG in detail

cfgdisable BForum_SAN1_CFG           #Disables the config BForum_SAN1_CFG

cfgremove “BForum_SAN1_CFG”,”BForum_HBA1_VNX_SPB2”           #Removes the zone BForum_HBA1_VNX_SPB2 from config BForum_SAN1_CFG

cfgactvshow            #Shows the current active config

alishow BForum_HBA1    #Shows the alias BForum_HBA1

zoneshow BForum_HBA1_VNX_SPA3   #Shows the zone BForum_HBA1_VNX_SPA3 details

More in coming posts. You may click here for SAN switch related posts. Thanks for reading..

 

Cisco MDS SAN switch Zoning via CLI

Here let’s discuss the steps to complete the zoning of a new server in Cisco MDS FC switch. In our previous post we had discussed the initialization procedure for a new MDS switch – may be helpful for you. The process of zoning will have 3 components, namely aliases, zones and zoneset (or zone configuration).

If you have a Brocade switch, you may refer to this post which explains zoning in a Brocade switch via CLI.

An alias is a name assigned to the WWN numbers which makes it easy to use/remember. WWN numbers Read more

– identity for a device, will have numbers separated by colon (:), for e.g, 10:ab:cd:ef:12:34:56:78 – are harder to be remembered.

A zone will be containing multiple objects which defines a communication path. In a zoning enabled switch, any two WWNs or port which are not having a common zone (which are not part of a single zone together) will not be able to communicate each other. We will create a Zone and will add the objects (WWNs, aliases or ports) to it.

A zoneset or a zone configuration is a collection of a set of zones in a switch/fabric. It makes easy to manage the zones. We will define an active configuration in switch/fabric and will add the zones, which need to be active, to this configuration.
Now let’s discuss the commands.

 

 

First we will create an alias for the new server HBA and the storage port to which it need to communicate.

#conifg -t

BForum_SAN01(config)# fcalias name BForum_HBA1 vsan 20        # This will create an alias with name BForum_HBA1

BForum_SAN01(config-alias)# member pwwn 10:xx:xx:xx:xx:xx:xx:01    # Adds the WWN to this alias

BForum_SAN01(config-alias)#exit

BForum_SAN01(config)# fcalias name VNX_SPA3 vsan 20

BForum_SAN01(config-alias)# member pwwn 50:xx:xx:xx:xx:xx:xx:01

BForum_SAN01(config-alias)#exit

Now we have the aliases ready. We can now create a zone for these two objects and add them. We will create a zone named ‘BForum_HBA1_VNX_SPA3’ which will be containing the host HBA (BForum_HBA1) and the storage port (VNX_SPA3).

BForum_SAN01(config)# zone name BForum_HBA1_VNX_SPA3 vsan 20

BForum_SAN01(config-zone)# member fcalias BForum_HBA1

BForum_SAN01(config-zone)# member fcalias VNX_SPA3

BForum_SAN01(config-zone)# exit

Zone too is ready now. Assuming we don’t have an existing configuration, we will be creating a zone config here. If you are already having a zoneset, you can use the zoneset name here in the below command.

 

 

BForum_SAN01(config)#zoneset name BForum_SAN01_Config VSAN 20

BForum_SAN01(config-zoneset)# member BForum_HBA1_VNX_SPA3

BForum_SAN01(config-zoneset)# exit

Now we have the zoneset created and zones added to it. We are good to activate the new zoneset.

BForum_SAN01(config)# zoneset activate name BForum_SAN01_Config VSAN 20

To verify the active zoneset, you may run the command show active zoneset

In case if you have to deactivate the zoneset, you may run the command,

BForum_SAN01(config)# no zoneset activate name BForum_SAN01_Config VSAN 20

We can save the running config to start-up config by running copy run start command. Now we have the zoning completed for one of the HBA of the new server. We will have to do the zoning for both the HBAs and should use multiple storage ports for redundancy.

You may click here for SAN switch related posts.

Hope this post was helpful for you. More, in coming posts, your thoughts in comments below… 🙂

Initializing a Cisco MDS FC switch

Trouble in initializing brand new Cisco MDS FC switch ? This post may help you. This post here discusses the procedure to initialize a new FC switch.

MDS_9124

You have to connect the Console cable with Read more

the serial (COM) port on your laptop/desktop. You may use any terminal emulation utility such as Putty, Hyper Terminal etc.. and should use the default settings for serial connection (9600 baud,8 data bits,1 stop bit,No parity). Now you are all set to receive get the serial console.

 

Now you can connect the power and switch the switch ON. Once the switch is powered ON and booted up, you will asked to set the password for administrator. You should be setting a strong password otherwise the entered one will be rejected.

Once this is done, you will be prompted whether or not to continue with entering the configuration data. You can proceed with yes once you have the necessary information.

 

 

Press Enter at anytime to skip a dialog. Use ctrl-c at anytime
to skip the remaining dialogs.

Would you like to enter the basic configuration dialog (yes/no): yes

Create another login account (yes/no) [n]:

Configure read-only SNMP community string (yes/no) [n]:

Configure read-write SNMP community string (yes/no) [n]:

Enter the switch name : B-Forum-SW01

Continue with Out-of-band (mgmt0) management configuration? (yes/no) [y]:

Mgmt0 IPv4 address : 12x.23x.234.123

Mgmt0 IPv4 netmask : 255.255.255.0

Configure the default gateway? (yes/no) [y]:

IPv4 address of the default gateway : 12x.23x.234.1

Configure advanced IP options? (yes/no) [n]:

Enable the ssh service? (yes/no) [y]:

===== Output shortened =====

 

 

The switch will be showing all the parameters going  to be set on the switch. If you need to edit any of them, you may enter yes for the query to edit. If you are OK with the values, you can go for the default , no.You can save the configuration by entering yes to the next query.

Would you like to edit the configuration? (yes/no) [n]: no

Use this configuration and save it? (yes/no) [y]: yes

The switch will reboot and the new configuration will take affect. Yes, we are done..

If you wish to reset these values later, you may try the command setup. You will be receiving the same questionnaire as you did for the first time initialization.

You may click here for SAN switch related posts.

Hope this post was helpful for you. Comments are always welcome…