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.