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.

Hitachi VSP Auto Dump Collection

We had posted previously on log collection from Hitachi unified storage and EMC VNX/Cellera storage arrays. In the same way, let us see how we can gather Auto Dump from Hitachi VSP storage arrays.

An Auto dump is a support log which is a mandate to analyse any kind of issue occurred on a Hitachi VSP Storage system. It is necessary to have Auto Dump collected during or shortly after an issue occurrence.

Read more

Normal Auto Dump can be collected by the customer and for detailed Auto dump you can take assistance from an HDS engineer.

For collecting an Auto Dump we need to have the SVP access, we can take an RDP session into the SVP. Basically, SVP is a Windows Vista system. Login to the SVP using the credentials.

Once you are logged in to the SVP you may either able to see the SVP console or the storage navigator Web console. If it is a storage navigator web console then go to “Maintenance” tab and select “Maintenance component General” It will open SVP console for you.

In the console, you can navigate to Auto Dump and you can click on the auto dump option to collect the log. You will be taken to a new window and you will be prompted to enter the target file location.

Once auto dump is started, it may take 30-45 minutes to complete.  Once it is completed you can navigate to C:\DKCxxx\TMP and you will find a file named hdcp.tgz last modified today (or the date you run the auto dump).

You can copy the file to your local PC or any server where internet connection is available.

Once we have files in our local system, we can upload the same to Hitachi Technical Upload Facility (TUF). This will require a valid Hitachi support case ID.

Hope this helped you. Feel free to provide your feedback in the comments section.

Expanding a (EMC Celerra/VNX) NAS Pool

In this post let’s discuss expanding a (EMC Celerra/VNX-File) NAS pool by adding new LUNs from the backend storage. A NAS Pool from on which we create Filesystems for NFS/CIFS (SMB) should have sufficient space for catering the NAS requests. Here our pool is running out of space, with only a few MBs left.

[[email protected] ~]$ nas_pool -size Bforum_Pool
id = 48
name = Bforum_Pool
used_mb = 491127
avail_mb = 123
total_mb = 491250
potential_mb = 0
[[email protected] ~]$

Let’s see how we can get this pool extended.

Read more

Let’s have a look first at the existing disks (LUNs from backend). Here we already have 9 disks assigned. We should have the 10th one in place, which will add up space to the pool.

[[email protected] ~]$ nas_disk -l
id inuse sizeMB storageID-devID type name servers
1 y 11263 CKxxxxxxxxxxx-0000 CLSTD root_disk 1,2
2 y 11263 CKxxxxxxxxxxx-0001 CLSTD root_ldisk 1,2
3 y 2047 CKxxxxxxxxxxx-0002 CLSTD d3 1,2
4 y 2047 CKxxxxxxxxxxx-0003 CLSTD d4 1,2
5 y 2047 CKxxxxxxxxxxx-0004 CLSTD d5 1,2
6 y 32767 CKxxxxxxxxxxx-0005 CLSTD d6 1,2
7 y 178473 CKxxxxxxxxxxx-0010 CLSTD d7 1,2
8 n 178473 CKxxxxxxxxxxx-0011 CLSTD d8 1,2
9 y 547418 CKxxxxxxxxxxx-0007 CLSTD d9 1,2
[[email protected] ~]$

As per the requirement, we have to assign the LUNs from the backend storage. It is recommended to add the new LUNs of identical size as of existing LUNs in the pool to have best performance.

Now to the most important part – Rescaning the new disks. We have to use the server_devconfig command for rescan. We can run the command against individual data movers also. The recommeded way to do this is to start with the standby DMs first and then on primary ones. Listing the nas_disks will show the servers on which the disks are scanned.

[[email protected] ~]$ server_devconfig ALL -create -scsi -all

Discovering storage (may take several minutes)
server_2 : done
server_3 : done
[[email protected] ~]$

Yes, that is done successfully. Now let’s check the disks list. We can see the 10th disk with inuse=n which is scanned on both servers (data movers).

[[email protected] ~]$ nas_disk -l
id inuse sizeMB storageID-devID type name servers
1 y 11263 CKxxxxxxxxxxx-0000 CLSTD root_disk 1,2
2 y 11263 CKxxxxxxxxxxx-0001 CLSTD root_ldisk 1,2
3 y 2047 CKxxxxxxxxxxx-0002 CLSTD d3 1,2
4 y 2047 CKxxxxxxxxxxx-0003 CLSTD d4 1,2
5 y 2047 CKxxxxxxxxxxx-0004 CLSTD d5 1,2
6 y 32767 CKxxxxxxxxxxx-0005 CLSTD d6 1,2
7 y 178473 CKxxxxxxxxxxx-0010 CLSTD d7 1,2
8 n 178473 CKxxxxxxxxxxx-0011 CLSTD d8 1,2
9 y 547418 CKxxxxxxxxxxx-0007 CLSTD d9 1,2
10 n 547418 CKxxxxxxxxxxx-0006 CLSTD d10 1,2
[[email protected] ~]$

Let’s check the pool again to see the available and potential storage capacity.

[[email protected] ~]$ nas_pool -size Bforum_Pool
id = 48
name = Bforum_Pool
used_mb = 491127
avail_mb = 123
total_mb = 491250
potential_mb = 547418
[[email protected] ~]$

Now, as you see, the expanded capacity is available in the pool (refer the potential storage) .

You may refer to our previous post on scanning new LUNs on VNX File/Celerra Data movers. click here for more Celerra/VNX posts.

ISILON basic commands

Here in this post, we are discussing a few basic isilon commands. Some of which comes to our help in our daily administration tasks for managing and monitoring the isilon array. You may refer the Celerra/VNX health check steps also we discussed in one of our previous posts.

Here are some of the isilon commands.

isi status : Displays the status of the cluster,nodes and events etc… You can use various options including -r (for displaying raw size), -D (for detailed info) -n (info for specific node -n <node id>)

isi_for_array : For running various commands against specific nodes. -n for a specific node and

isi events : There are many options with the ‘events’ command including isi events list (to list all the events) isi events cancel (to cancel the events) isi events quiet (to quiet the events). You can setup event notifications also using the isi events command.

Read more

isi devices : To view and change the cluster devices status. There are plenty of options with the devices command.

isi devices –device <Device>  : where Device can be a drive or an entire node. –action option is used to perform any specific option on the devices (–action <action>) including smartfail, stopfail, status, add, format etc…

isi firmware status : is used to list the isilon firmware type and versions.

isi nfs exports : NFS exports command is used for various isilon NFS operations including export creation, listing/viewing modifying etc… Below are a list of sub-commands.

1. isi nfs exports create –zone <zone name> –root-clients=host1, host2 –read-write-clients=host2, host3 –path=<path>

2. isi nfs exports view <export ID> –zone=<zone name>

3. isi nfs exports modify <export ID> –zone=<zone name> –add-read-write-clients host4

isi smb share : This command is used to create, list/view, modify etc… operations on SMB shares. Sample sub-commands –

1. isi smb shares create <share name> –path=/ifs/data/SMBpath –create-path –browsable=true –zone <zone name> –description=”Test share”

2. isi smb shares delete <share name> –zone=<zone name>

isi quota quotas : this command is used for various quota operations including creation/deletion/modification etc…

Hope this post helped you. Please feel free to comment if you have any questions. We will discuss more detailed commands in a later post.

 

Way to gather simple trace from Hitachi Unified Storage

You may refer our previous post on VNX/Cellera log collection. Here we can see how to gather support logs from Hitachi Unified Storage (HUS 110, HUS 130 & HUS 150).

A “Simple Trace” is needed for analysis of all issues relating to the Hitachi storage systems. The trace can be obtained by the customer. It is critical to gather a trace as soon as possible after a problem is detected. This is to prevent log data wrapping and loss of critical information.

Read more

If a performance problem is being experienced, take one simple trace as soon as possible, while performance is affected. This can assist greatly in finding the root cause

 

Hitachi modular storage (HUS/AMS) log collection is a very simple task.

We can login to the WEB GUI using the controller IP Address (type the controller IP Address in a web browser and press enter). both HUS controllers have IP Address. Then in the left panel of the WEB GUI we can find “Simple Trace” Under Trace.

HUS Log Collection

Click on the simple trace and it will pop-up a screen, here will take some time to get it generated. We can monitor the percentage from the pop-up screen. Once the fetching completed we can download it to our local system. There may be multiple files we have to download for complete information from the same pop-up.

The file name will be as follows  smpl_trc1_systemserialnumber_yyyymmdd.dat 

Once we have files in our local system, we can upload the same to Hitachi Technical Upload Facility (TUF) Here we requires valid support case ID from Hitachi.

 

 

1 2 3 4