0% found this document useful (0 votes)
20 views90 pages

Big Data Analytics M.Sc. IT Practices

The document is a practical journal for M.Sc. (Information Technology) Part-I students at Pillai HOC College, focusing on Big Data Analytics. It includes a series of practical exercises related to Hadoop installation, MapReduce programming, and data manipulation using HBase and MongoDB. The journal is submitted by Aditya Rupesh Koli for the academic year 2024-2025 and outlines various tasks and configurations necessary for big data projects.

Uploaded by

bharkalerushiraj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views90 pages

Big Data Analytics M.Sc. IT Practices

The document is a practical journal for M.Sc. (Information Technology) Part-I students at Pillai HOC College, focusing on Big Data Analytics. It includes a series of practical exercises related to Hadoop installation, MapReduce programming, and data manipulation using HBase and MongoDB. The journal is submitted by Aditya Rupesh Koli for the academic year 2024-2025 and outlines various tasks and configurations necessary for big data projects.

Uploaded by

bharkalerushiraj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

PILLAI HOC COLLEGE OF ART, SCIENCE & COMMERCE

UNIVERSITY OF MUMBAI
BIG DATA ANALYTICS, MODERN NETWORKING &
COMPUTER VISION
[Link]. (Information Technology) Part-I

Submitted by
Aditya Rupesh Koli
Seat No: 1312543

DEPARTMENT OF INFORMATION TECHNOLOGY


PILLAI HOC COLLEGE OF ART, SCIENCE & COMMERCE, RASAYANI
NAAC Accredited 'A+' Grade, Cycle II & ISO 9001:2015 Certified
(Affiliated to Mumbai University)
RASAYANI-410207, MAHARASHTRA
2024-2025
PILLAI HOC COLLEGE OF ART, SCIENCE & COMMERCE
UNIVERSITY OF MUMBAI
BIG DATA ANALYTICS
[Link]. (Information Technology) Part-I

Submitted by
Aditya Rupesh Koli
Seat No: 1312543

DEPARTMENT OF INFORMATION TECHNOLOGY


PILLAI HOC COLLEGE OF ART, SCIENCE & COMMERCE, RASAYANI
NAAC Accredited 'A+' Grade, Cycle II & ISO 9001:2015 Certified
(Affiliated to Mumbai University)
RASAYANI-410207, MAHARASHTRA
2024-2025
MAHATMA EDUCATION SOCIETY’S
PILLAI HOC COLLEGE OF ART, SCIENCE & COMMERCE, RASAYANI
NAAC Accredited 'A+' Grade, Cycle II & ISO 9001:2015 Certified
(Affiliated to Mumbai University)
RASAYANI-410207, MAHARASHTRA

INFORMATION TECHNOLOGY

CERTIFICATE
This is to certify that the experiment work entered in this journal is as per the syllabus
in [Link]. (Information Technology) Part-I, Semester-II; class prescribed by
University of Mumbai for Big Data Analytics, of Mahatma Education Society’s
Pillai HOC College of Arts, Science & Commerce, Rasayani by Aditya Rupesh
Koli during Academic year 2024-2025.
Seat No: 1312543

In-Charge Co-Ordinator

External Examiner Principal

Date College Seal


BIG DATA ANALYTICS
INDEX
Practical Title Date Page Signature
No. No.
01 Install, configure and run Hadoop 01
and HDFS and explore HDFS on
Windows.
02 Implement word count / frequency 06
programs using MapReduce
03 Implement an application that stores 07
big data in HBase / MongoDB and
manipulate it using R / Python
04 Implement Decision Tree 11
classification techniques
05 Implement SVM classification 13
techniques
06 REGRESSION MODEL: Import a 14
dataset from web storage. Do Logistic
Regression to find relation between
variables affecting student admission
based on GRE score, GPA, and rank.
Check if the model is fit using require
(foreign) and require (MASS)
07 MULTIPLE REGRESSION 16
MODEL: Apply multiple regression
if data have a continuous
independent variable. Apply on the
above dataset.
08 CLASSIFICATION MODEL: 17
a. Install relevant package for
classification.
b. Choose classifier.
c. Evaluate performance.
09 CLUSTERING MODEL: 18
a. Use clustering algorithms for
unsupervised classification.
b. Plot cluster data using R
visualizations.
Big Data Analytics [Link] Sem-2

PRACTICAL NO: 01
AIM: Install, configure and run Hadoop and HDFS and explore HDFS on Windows
Steps to Install Hadoop
1. Install Java JDK 1.8
2. Download Hadoop and extract and place under C drive
3. Set Path in Environment Variables
4. Config files under Hadoop directory
5. Create folder datanode and namenode under data directory
6. Edit HDFS and YARN files
7. Set Java Home environment in Hadoop environment
8. Setup Complete. Test by executing [Link]
There are two ways to install Hadoop, i.e.
9. Single node
10. Multi node
Here, we use multi node cluster.
1. Install Java
11. – Java JDK Link to download [Link]
[Link]
12. – extract and install Java in C:\Java
13. – open cmd and type -> javac -version

2. Download Hadoop
[Link] [Link]
right click .[Link] file -> show more options -> 7-zip->and extract to C:\Hadoop- 3.3.0\

3. Set the path JAVA_HOME Environment variable


4. Set the path HADOOP_HOME Environment variable

Pillai HOC College of Art, Science and Commerce Page | 1


Big Data Analytics [Link] Sem-2

Click on New to both user variables and system variables.

Click on user variable -> path -> edit-> add path for Hadoop and java upto “bin‟
Click Ok, Ok, Ok.
5. Configurations
Edit file C:/Hadoop-3.3.0/etc/hadoop/[Link], paste the xml code in folder and save
<configuration>
<property>
<name>[Link]</name>
<value>hdfs://localhost:9000</value>
</property>
</configuration>
Rename “[Link]” to “[Link]” and edit this file
C:/Hadoop3.3.0/etc/hadoop/[Link], paste xml code and save this file.
<configuration>
<property>
<name>[Link]</name>
<value>yarn</value>
</property>
</configuration>
Create folder “data” under “C:\Hadoop-3.3.0”

Create folder “datanode” under “C:\Hadoop-3.3.0\data”

Pillai HOC College of Art, Science and Commerce Page | 2


Big Data Analytics [Link] Sem-2

Create folder “namenode” under “C:\Hadoop-3.3.0\data”


Edit file C:\Hadoop-3.3.0/etc/hadoop/[Link], paste xml code and save this file.
<configuration>
<property>
<name>[Link]</name>
<value>1</value>
</property>
<property>
<name>[Link]</name>
<value>/hadoop-3.3.0/data/namenode</value>
</property>
<property>
<name>[Link]</name>
<value>/hadoop-3.3.0/data/datanode</value>
</property>
</configuration>
Edit file C:/Hadoop-3.3.0/etc/hadoop/[Link], paste xml code and save this file.
<configuration>
<property>
<name>[Link]-services</name>
<value>mapreduce_shuffle</value>
</property>
<property>
<name>[Link]</name>
<value>[Link]</value>
</property>
<property>
<name>[Link]</name>
<value>[Link]:8032</value>
<name>[Link]</name>
<value>[Link]:8030</value>
<name>[Link]</name>
<value>[Link]:8031</value>
</property>
</configuration>
6. Edit file C:/Hadoop-3.3.0/etc/hadoop/[Link]
Find “JAVA_HOME=%JAVA_HOME%” and replace it as
set JAVA_HOME="C:\Java\jdk1.8.0_361"
7. Download “redistributable” package
Download and run VC_redist.[Link]
This is a “redistributable” package of the Visual C runtime code for 64-bit applications, from
Microsoft. It contains certain shared code that every application written with Visual C
expects to have available on the Windows computer it runs on.
8. Hadoop Configurations
Download bin folder from [Link]
– Copy the bin folder to c:\hadoop-3.3.0. Replace the existing bin folder.

Pillai HOC College of Art, Science and Commerce Page | 3


Big Data Analytics [Link] Sem-2

9. copy "[Link]" from ~\hadoop-


3.0.3\share\hadoop\yarn\timelineservice to ~\hadoop-3.0.3\share\hadoop\yarn folder.

10. Format the NameNode


– Open cmd „Run as Administrator‟ and type command “hdfs namenode –format”
11. Testing
– Open cmd „Run as Administrator‟ and change directory to C:\Hadoop-3.3.0\sbin
– type [Link] OR type [Link]
– type [Link]
– You will get 4 more running threads for Datanode, namenode, resouce manager and
node manager

Output:

Pillai HOC College of Art, Science and Commerce Page | 4


Big Data Analytics [Link] Sem-2

12. Type JPS command to [Link] command prompt, you will get following output.
13. Run [Link] from any browser

Pillai HOC College of Art, Science and Commerce Page | 5


Big Data Analytics [Link] Sem-2

PRACTICAL NO: 02
AIM: Implement word count / frequency programs using Map Reduce .
Steps:
• C:\hadoop-3.3.0\sbin>[Link]
• C:\hadoop-3.3.0\sbin>[Link]
• Open a command prompt as administrator and run the following command to create an
input and output folder on the Hadoop file system, to which we will be moving the
[Link] file for our analysis.
• C:\hadoop-3.3.0\bin>cd\
• C:\>hadoop dfsadmin -safemode leave
• DEPRECATED: Use of this script to execute hdfs command is deprecated.
• Instead use the hdfs command for it.
• Safe mode is OFF
• C:\>hadoop fs -mkdir /input_dir
• Check it by giving the following URL at browser [Link]
• Now apply the following command at c:\>
• C:\> hadoop fs -put C:/input_file.txt /input_dir
• Verify input_file.txt available in HDFS input directory (input_dir).
C:\>Hadoop fs -ls /input_dir/
• C:\>hadoop jar C:/hadoop-3.3.0/share/hadoop/mapreduce/hadoop-mapreduce-examples-
[Link] wordcount /input_dir /output_dir
• In case, there is some error in executing then copy the file [Link] in C:\
and run the program with the jar file using existing [Link] file as:
• C:\> hadoop jar C:/[Link] wordcount /input_dir /output_dir
• Now, check the output_dir on browser as follows:
• Click on output_dir à part-r-00000 à Head the file (first 32 K) and check the file content
as the output.
• Alternatively, you may type the following command on CMD window as:
• C:\> hadoop dfs -cat /output_dir/*
You can get the following output
Output:

Pillai HOC College of Art, Science and Commerce Page | 6


Big Data Analytics [Link] Sem-2

PRACTICAL NO: 03
AIM: Implement an application that stores big data in Hbase / MongoDB and
manipulate it using R / Python
Requirements
a. PyMongo
b. Mongo Database
Install Mongo database
Step 1: Go to ([Link] and Download
MongoDB Community Server. We will install the 64-bit version for Windows.

Step 2: Once download is complete open the msi file. Click Next in the start up screen

Step 3: Accept the End-User License Agreement. Click Next


Step 4: Click on the "complete" button to install all of the components. The custom option
can be used to install selective components or if you want to change the location of the
installation.
Step 5: Select “Run service as Network Service user”. make a note of the data directory,
we”ll need this later.
Step 6: Click on the Install button to start the installation.

Step 7: Installation begins. Click Next once completed.

Pillai HOC College of Art, Science and Commerce Page | 7


Big Data Analytics [Link] Sem-2

Step 8: Click on the Finish button to complete the installation.

Test Mongodb:
Step 1: Go to " C:\Program Files\MongoDB\Server\4.0\bin" and double click on
[Link].
Alternatively, you can also click on the MongoDB desktop icon.
Create the directory where MongoDB will store its files.
Open command prompt window and apply following commands
C:\users\admin> cd\
C:\>md data\db
Step 2: Execute mongodb
Open another command prompt window.
C:\> cd C:\Program Files\MongoDB\Server\4.0\bin
C:\Program Files\MongoDB\Server\4.0\bin> mongod
In case if it gives an error then run the following command:
C:\Program Files\MongoDB\Server\4.0\bin> mongod –repair

Step 3: Connect to MongoDB using the Mongo shell


Let the MongoDB daemon to run.
Open another command prompt window and run the following commands:
C:\users\admin> cd C:\Program Files\MongoDB\Server\4.0\bin
C:\Program Files\MongoDB\Server\4.0\bin>mongo

Step 4: Install PyMongo


Open another command prompt window and run the following commands:
Check the python version on your desktop / laptop and copy that path from window explorer
C:\users\admin>cd C:\Program Files\Python311\Scripts

Pillai HOC College of Art, Science and Commerce Page | 8


Big Data Analytics [Link] Sem-2

C:\Program Files\<Python38>\Scripts > python -m pip install pymongo

Note: # -m option is for <module-name>


Now you have downloaded and installed a mongoDB driver.
Step 5: Test PyMongo
Run the following command from python command prompt
import pymongo
Now, either create a file in Python IDLE or run all commands one by one in sequence on
Python cell
Program 1: Creating a Database: create_dp.py
import pymongo
myclient = [Link]("mongodb://localhost:27017/")
mydb = myclient["mybigdata"]
print(myclient.list_database_names())

Progam 2: Creating a Collection: create_collection.py


import pymongo
myclient = [Link]("mongodb://localhost:27017/")
mydb = myclient["mybigdata"]
mycol=mydb["student"]
print(mydb.list_collection_names())

Progam 3: Insert into Collection: insert_into_collection.py


import pymongo
myclient = [Link]("mongodb://localhost:27017/")
mydb = myclient["mybigdata"]
mycol=mydb["student"]
mydict={"name":"Beena", "address":"Mumbai"}
x=mycol.insert_one(mydict) # insert_one(containing the name(s) and value(s) of each field
Program 4: Insert Multiple data into Collection: insert_many.py
import pymongo
myclient = [Link]("mongodb://localhost:27017/")
mydb = myclient["mybigdata"]
mycol=mydb["student"]
mylist=[{"name":"Khyati", "address":"Mumbai"}, {"name":"Kruti", "address":"Mumbai"},
{"name":"Nidhi", "address":"Pune"}, {"name":"Komal", "address":"Pune"},]
x=mycol.insert_many(mylist)
Step 6: Test in Mongodb to check database and data inserted in collection
a. If you want to check your database list, use the command show dbs in mongo
command prompt

Pillai HOC College of Art, Science and Commerce Page | 9


Big Data Analytics [Link] Sem-2

> show dbs

b. If you want to use a database with name mybigdata, then use database
statement would be as follow:
> use mybigdata

c. If you want to check collection in mongodb use the command show collections
> show collections

d. If you want to display the first row from collection: db.collection_name.find()


> [Link]()

e. If you want to display all the data from collection: db.collection_name.find()


> [Link]()

f. count number of rows in a collection


> [Link]()

Site for R packages documentation:


[Link]

Pillai HOC College of Art, Science and Commerce Page | 10


Big Data Analytics [Link] Sem-2

PRACTICAL NO: 04
AIM: A) Implement Decision Tree classification technique using Social_Network_Ads.csv
dataset.
# Decision Tree Classification
# Importing the dataset
dataset = [Link]("D:\\bda prac\\Social_Network_Ads.csv")
#print(dataset)
dataset = dataset[3:5] # columns 3 4 ad 5
print(dataset)
# Encoding the target feature as factor(just like a vector having levels
# levels to convey that only two possible values for purchased - 0 & 1
dataset$Purchased = factor(dataset$Purchased, levels = c(0, 1))
print (dataset$Purchased)
# Splitting the dataset into the Training set and Test set
[Link]('caTools')
library(caTools)
[Link](123)
#split = [Link](dataset$Purchased, SplitRatio = 0.75)
split = [Link](dataset$Purchased, SplitRatio = 0.75)
training_set = subset(dataset, split == TRUE)
test_set = subset(dataset, split == FALSE)
#Feature Scaling - scale() method centers and/or scales the columns of a numeric matrix.
training_set[-3] = scale(training_set[-3]) # scaling first 2 columns, don't consider 3rd column
test_set[-3] = scale(test_set[-3])
#print(test_set[-3])
# Fitting Decision Tree Classification to the Training set
[Link]('rpart')
library(rpart) # for partitioning tree
[Link]('[Link]')
library([Link])
classifier = rpart(formula = Purchased ~ .,data = training_set)
# Predicting the Test set results
y_pred = predict(classifier, newdata = test_set[-3], type = 'class')
print(y_pred)
# Making the Confusion Matrix
cm = table(test_set[, 3], y_pred)
print(cm)
y_grid = predict(classifier, newdata = grid_set, type = 'class')
# Plotting the tree
#extra=106 class model with a binary response
#extra=104 class model with a response having more than two levels
[Link](classifier, extra = 106)

Pillai HOC College of Art, Science and Commerce Page | 11


Big Data Analytics [Link] Sem-2

Output:

Pillai HOC College of Art, Science and Commerce Page | 12


Big Data Analytics [Link] Sem-2

PRACTICAL NO: 05
AIM: B) Implement SVM Classification technique using Social_Network_Ads.csv dataset.
Evaluate the performance of classifier.
# Support Vector Machine (SVM)
# Importing the dataset
dataset = [Link]("D:\\bda prac\\Social_Network_Ads.csv")
dataset = dataset[3:5]
print(dataset)
print(dataset$Purchased)
# Splitting the dataset into the Training set and Test set
[Link]('caTools')
library(caTools)
[Link](123)
split = [Link](dataset$Purchased, SplitRatio = 0.75)
training_set = subset(dataset, split == TRUE)
print(training_set)
test_set = subset(dataset, split == FALSE)
print(test_set)
# Feature Scaling
training_set[-3] = scale(training_set[-3]) # [-3] means 3rd index will be dropped
test_set[-3] = scale(test_set[-3])
print(training_set[-3])
print (test_set[-3])
# Fitting SVM to the Training set
[Link]('e1071')
library(e1071)
classifier = svm(formula = Purchased ~ .,
data = training_set,
type = 'C-classification',
kernel = 'linear')
print (classifier)
# Predicting the Test set results
y_pred = predict(classifier, newdata = test_set[-3])
print(y_pred)
# Making the Confusion Matrix
cm = table(test_set[, 3], y_pred)
print (cm)
Output:

Pillai HOC College of Art, Science and Commerce Page | 13


Big Data Analytics [Link] Sem-2

PRACTICAL NO: 06
AIM: REGRESSION MODEL Import a data from web storage. Name the dataset and now
do Logistic Regression to find out relation between variables that are affecting the
admission of a student in an institute based on his or her GRE score, GPA obtained and
rank of the student. Also check the model is fit or not. require (foreign), require(MASS).
#fetch the data
#fetch the data
college <- [Link]("[Link]
dlnd/master/nn/[Link]")
head(college)
nrow(college)
[Link]("caTools") # For Logistic regression
library(caTools)
split <- [Link](college, SplitRatio = 0.75) split
training_reg <- subset(college, split == "TRUE")
test_reg <- subset(college, split == "FALSE")
# Training model
fit_logistic_model <- glm(admit ~ ., data = training_reg, family = "binomial")
# Predict test data based on model
predict_reg <- predict(fit_logistic_model, test_reg, type = "response")
predict_reg
cdplot([Link](admit)~ gpa, data=college)
cdplot([Link](admit)~ gre, data=college)
cdplot([Link](admit)~ rank, data=college)
# Changing probabilities
predict_reg <- ifelse(predict_reg >0.5, 1, 0) predict_reg
# Evaluating model accuracy
# using confusion matrix
table(test_reg$admit, predict_reg)

Output:
Model:

Pillai HOC College of Art, Science and Commerce Page | 14


Big Data Analytics [Link] Sem-2

Confusion martrix:

Pillai HOC College of Art, Science and Commerce Page | 15


Big Data Analytics [Link] Sem-2

PRACTICAL NO: 07

AIM: Apply multiple regressions, if data have a continuous independent variable. Apply on
above dataset – [Link].
#fetch the data
college <- [Link]("[Link]
dlnd/master/nn/[Link]")
head(college)
nrow(college)
[Link]("caTools") # For Logistic regression
library(caTools)
split <- [Link](college, SplitRatio = 0.75) split
training_reg <- subset(college, split == "TRUE")
test_reg <- subset(college, split == "FALSE")
# Training model
fit_MRegressor_model <- lm(formula = admit ~ gre+gpa+rank, data = training_reg)
# Predict test data based on model
predict_reg <- predict(fit_MRegressor_model,newdata = test_reg)
predict_reg
cdplot([Link](admit)~ gpa, data=college)
cdplot([Link](admit)~ gre, data=college)
cdplot([Link](admit)~ rank, data=college)

Output:

Pillai HOC College of Art, Science and Commerce Page | 16


Big Data Analytics [Link] Sem-2

PRACTICAL NO: 08
AIM: CLASSIFICATION MODEL
a. Install relevant package for classification.
b. Choose classifier for classification problem.
c. Evaluate the performance of classifier
# # Naive Bayes
# Importing the dataset
dataset = [Link]('C:\\2022-23\\BDA practical 2023\\Social_Network_Ads.csv')
dataset = dataset[3:5]
# Encoding the target feature as factor
dataset$Purchased = factor(dataset$Purchased, levels = c(0, 1))
# Splitting the dataset into the Training set and Test set
#[Link]('caTools')
library(caTools)
[Link](123)
split = [Link](dataset$Purchased, SplitRatio = 0.75)
training_set = subset(dataset, split == TRUE)
test_set = subset(dataset, split == FALSE)
# Feature Scaling
training_set[-3] = scale(training_set[-3])
test_set[-3] = scale(test_set[-3])
# Fitting Naive Bayes to the Training set
[Link]('e1071')
library(e1071)
classifier = naiveBayes(x = training_set[-3], y = training_set$Purchased)
# Predicting the Test set results
y_pred = predict(classifier, newdata = test_set[-3])
# Making the Confusion Matrix
cm = table(test_set[, 3], y_pred)
print(cm)
Output:

Pillai HOC College of Art, Science and Commerce Page | 17


Big Data Analytics [Link] Sem-2

PRACTICAL NO: 09
Aim: A) Clustering algorithms for unsupervised classification. Read a datafile
all_Customers.csv and apply k-means clustering. Plot the cluster data using R
visualizations.
# K-Means Clustering
# Importing the dataset
dataset = [Link]("D:\\bda prac\\Mall_Customers.csv")
head(dataset)
dataset = dataset[4:5]
head(dataset)
wcss = vector()
for (i in 1:10) wcss[i] = sum(kmeans(dataset, i)$withinss)
plot(1:10,
type = 'b',
main = paste('The Elbow Method'),
xlab = 'Number of clusters',
ylab = 'WSS')
# Fitting K-Means to the dataset with no of clusters = 5
kmeans = kmeans(x = dataset, centers = 5)
y_kmeans = kmeans$cluster
library(cluster)
clusplot(dataset,
y_kmeans,
lines = 0,
shade = TRUE,
color = TRUE,
labels = 2,
main = paste('Clusters of customers'),
xlab = 'Annual Income',
ylab = 'Spending Score')
Output:

Pillai HOC College of Art, Science and Commerce Page | 18


PILLAI HOC COLLEGE OF ART, SCIENCE & COMMERCE
UNIVERSITY OF MUMBAI
MODERN NETWORKING
[Link]. (Information Technology) Part-I

Submitted by
Aditya Rupesh Koli
Seat No: 1312543

DEPARTMENT OF INFORMATION TECHNOLOGY


PILLAI HOC COLLEGE OF ART, SCIENCE & COMMERCE, RASAYANI
NAAC Accredited 'A+' Grade, Cycle II & ISO 9001:2015 Certified
(Affiliated to Mumbai University)
RASAYANI-410207, MAHARASHTRA
2024-2025
MAHATMA EDUCATION SOCIETY’S
PILLAI HOC COLLEGE OF ART, SCIENCE & COMMERCE, RASAYANI
NAAC Accredited 'A+' Grade, Cycle II & ISO 9001:2015 Certified
(Affiliated to Mumbai University)
RASAYANI-410207, MAHARASHTRA

INFORMATION TECHNOLOGY

CERTIFICATE
This is to certify that the experiment work entered in this journal is as per the syllabus
in [Link]. (Information Technology) Part-I, Semester-II; class prescribed by
University of Mumbai for Modern Netwrking, of Mahatma Education Society’s
Pillai HOC College of Arts, Science & Commerce, Rasayani by Aditya Rupesh
Koli during Academic year 2024-2025.
Seat No: 1312543

In-Charge Co-Ordinator

External Examiner Principal

Date College Seal


MODERN NETWORKING
INDEX
Practical Title Date Page Signature
No. No.
01 Configure IP SLA Tracking and 01
Path Control
02 Use the AS_PATH attribute to 12
filter BGP routes
03 Configuring IBGP and EBGP 17
Sessions, Local Preference, and
MED
04 Secure the Management Plane 22
05 Configure and Verify Path 28
Control
06 Configure IP SLA Tracking and 32
Path Control with Gateway
07 Configuring Basic MPLS Using 36
OSPF
Modern Networking [Link] Sem-2

PRACTICAL NO: 01
AIM: Configure IP SLA Tracking and Path Control
Topology

Objectives

• Configure and verify the IP SLA feature.


• Test the IP SLA tracking feature.
• Verify the configuration and operation using show and debug commands.
Background
You want to experiment with the Cisco IP Service Level Agreement (SLA) feature to study
how it could be of value to your organization.
At times, a link to an ISP could be operational, yet users cannot connect to any other outside
Internet resources. The problem might be with the ISP or downstream from them. Although
policy-based routing (PBR) can be implemented to alter path control, you will implement the
Cisco IOS SLA feature to monitor this behavior and intervene by injecting another default
route to a backup ISP.
To test this, you have set up a three-router topology in a lab environment. Router R1
represents a branch office connected to two different ISPs. ISP1 is the preferred connection to
the Internet, while ISP2 provides a backup link. ISP1 and ISP2 can also interconnect, and
both can reach the web server. To monitor ISP1 for failure, you will configure IP SLA probes
to track the reachability to the ISP1 DNS server. If connectivity to the ISP1 server fails, the
SLA probes detect the failure and alter the default static route to point to the ISP2 server.
Note: This lab uses Cisco 1841 routers with Cisco IOS Release 12.4(24) T1 and the
Advanced IP Services image [Link]. You can use other
routers (such as a 2801 or 2811) and Cisco IOS Software versions if they have comparable
capabilities and features. Depending on the router and Cisco IOS Software version, the
commands available and output produced might vary from what is shown in this lab
failure, you will configure IP SLA probes to track the reachability to the ISP1 DNS server. If
connectivity to the ISP1 server fails, the SLA probes detect the failure and alter the default
static route to point to the ISP2 server.
Note: This lab uses Cisco 1841 routers with Cisco IOS Release 12.4(24)T1 and the Advanced
IP Services image [Link]. You can use other routers (such
as a 2801 or 2811) and Cisco IOS Software versions if they have comparable capabilities and

Pillai HOC College of Art, Science and Commerce Page | 1


Modern Networking [Link] Sem-2

features. Depending on the router and Cisco IOS Software version, the commands available
and output produced might vary from what is shown in this lab.
Required Resources
• 3 routers (Cisco 1841 with Cisco IOS Release 12.4(24)T1 Advanced IP Services or
comparable)
• Serial and console cables
Step 1: Prepare the routers and configure the router hostname and interface addresses.
A]Cable the network as shown in the topology diagram. Erase the startup configuration
and reload each router to clear the previous configurations. Using the addressing
scheme in the diagram, create the loopback interfaces and apply IP addresses to them as
well as the serial interfaces on R1, ISP1, and ISP2.
You can copy and paste the following configurations into your routers to begin.
Note: Depending on the router model, interfaces might be numbered differently than
those listed. You might need to alter them accordingly.
Router R1
hostname R1
interface Loopback 0 description R1 LAN
ip address [Link] [Link]
interface Serial0/0/0 description R1 --> ISP1
ip address [Link] [Link]
clock rate 128000
bandwidth 128 no shutdown
interface Serial0/0/1 description R1 --> ISP2
ip address [Link] [Link]
bandwidth 128 no shutdown
Router ISP1 (R2)
hostname ISP1
interface Loopback0
description Simulated Internet Web Server ip address [Link] [Link]
interface Loopback1 description ISP1 DNS Server
ip address [Link] [Link]
interface Serial0/0/0 description ISP1 --> R1
ip address [Link] [Link]
bandwidth 128 no shutdown
interface Serial0/0/1 description ISP1 --> ISP2
ip address [Link] [Link]
clock rate 128000
bandwidth 128 no shutdown
Router ISP2 (R3)
hostname ISP2
interface Loopback0
description Simulated Internet Web Server ip address [Link] [Link]
interface Loopback1 description ISP2 DNS Server
ip address [Link] [Link]
interface Serial0/0/0 description ISP2 --> R1
ip address [Link] [Link]
clock rate 128000
bandwidth 128 no shutdown
interface Serial0/0/1 description ISP2 --> ISP1
ip address [Link] [Link]
bandwidth 128 no shutdown

Pillai HOC College of Art, Science and Commerce Page | 2


Modern Networking [Link] Sem-2

B] Verify the configuration by using the show interfaces description command. The output from
router R1 is shown here as an example.
R1# show interfaces description
Interface Fa0/0 Status admin down Protocol down Description
Fa0/1 admin down down
Se0/0/0 up up R1 --> ISP1
Se0/0/1 up up R1 --> ISP2
Lo0 up up R1 LAN
All three interfaces should be active. Troubleshoot if necessary.
C] The current routing policy in the topology is as follows:
• Router R1 establishes connectivity to the Internet through ISP1 using a default static route.
• ISP1 and ISP2 have dynamic routing enabled between them, advertising their respective
public address pools.
• ISP1 and ISP2 both have static routes back to the ISP LAN.
Note: For the purpose of this lab, the ISPs have a static route to an RFC 1918 private network
address on the branch router R1. In an actual branch implementation, Network Address
Translation (NAT) would be configured for all traffic exiting the branch LAN. Therefore, the
static routes on the ISP routers would be pointing to the provided public pool of the branch
office. This is covered in Lab 7-1, ―Configure Routing Facilities to the Branch Office.
Implement the routing policies on the respective routers. You can copy and paste the
following configurations.
Router R1
ip route [Link] [Link] [Link]
Router ISP1 (R2)
router eigrp 1
network [Link] [Link]
network [Link] [Link]
no auto-summary
ip route [Link] [Link] [Link]
Router ISP2 (R3)
router eigrp 1
network [Link] [Link]
network [Link] [Link]
no auto-summary
ip route [Link] [Link] [Link]
EIGRP neighbor relationship messages on ISP1 and ISP2 should be generated.
Troubleshoot if necessary.
%DUAL-5-NBRCHANGE: IP-EIGRP(0) 1: Neighbor [Link] (Serial0/0/1) is
up: new adjacency
Step 2: Verify server reachability.
The Cisco IOS IP SLA feature enables an administrator to monitor network performance
between Cisco devices (switches or routers) or from a Cisco device to a remote IP device.
foreach address {
[Link]
[Link]
[Link]
}{
ping $address source [Link]
}
R1(tcl)# foreach address {
+>(tcl)# [Link].

Pillai HOC College of Art, Science and Commerce Page | 3


Modern Networking [Link] Sem-2

+>(tcl)# [Link]
+>(tcl)# [Link]
+>(tcl)# } {
+>(tcl)# ping $address source [Link]
+>(tcl)#}
Type escape sequence to abort.
Sending 5, 100-byte ICMP Echos to [Link], timeout is 2 seconds: Packet sent with
a source address of [Link]
!!!!!
Success rate is 100 percent (5/5), round-trip min/avg/max = 12/15/16 ms Type escape
sequence to abort.
Sending 5, 100-byte ICMP Echos to [Link], timeout is 2 seconds: Packet sent with a
source address of [Link]
!!!!!
Success rate is 100 percent (5/5), round-trip min/avg/max = 12/14/16 ms Type escape
sequence to abort.
Sending 5, 100-byte ICMP Echos to [Link], timeout is 2 seconds: Packet sent with
a source address of [Link]
!!!!!
Success rate is 100 percent (5/5), round-trip min/avg/max = 20/21/24 ms
B] Trace the path taken to the web server, ISP1 DNS server, and ISP2 DNS server. You can
copy the following Tcl script and paste it into R1.
foreach address { [Link]
[Link]
[Link] } {
trace $address source [Link] }
R1(tcl)# foreach address {
+>(tcl)# [Link]
+>(tcl)# [Link]
+>(tcl)# [Link]
+>(tcl)# } {
+>(tcl)# trace $address source [Link]
+>(tcl)# }
Step 3: Configure IP SLA probes.
When the reachability tests are successful, you can configure the Cisco IOS IP SLAs probes.
Different types of probes can be created, including FTP, HTTP, and jitter probes. In this
scenario, you will configure ICMP echo probes.
A] Create an ICMP echo probe on R1 to the primary DNS server on ISP1 using the ip
sla command.
Note: With Cisco IOS Release 12.4(4)T, 12.2(33)SB, and 12.2(33)SXI, the ip sla command
has replaced the previous ip sla monitor command. In addition, the icmp-echo command has
replaced the type echo protocol ipIcmpEcho command.
R1(config)# ip sla 11
R1(config-ip-sla)# icmp-echo [Link]
R1(config-ip-sla-echo)# frequency 10
R1(config-ip-sla-echo)# exit
R1(config)# ip sla schedule 11 life forever start-time now
The operation number of 11 is only locally significant to the router. The frequency 10
command schedules the connectivity test to repeat every 10 seconds. The probe is scheduled
to start now and to run forever.

Pillai HOC College of Art, Science and Commerce Page | 4


Modern Networking [Link] Sem-2

B] Verify the IP SLAs configuration of operation 11 using the show ip sla configuration
11 command.
Note: With Cisco IOS Release 12.4(4)T, 12.2(33)SB, and 12.2(33)SXI, the show ip sla
configuration
command has replaced the show ip sla monitor configuration command.
R1# show ip sla configuration 11 IP SLAs, Infrastructure Engine-II. Entry number: 11
Owner:
Tag:
Type of operation to perform: icmp-echo
Target address/Source address: [Link]/[Link] Type Of Service parameter: 0x0
Request size (ARR data portion): 28 Operation timeout (milliseconds): 5000 Verify data: No
Vrf Name:
Schedule:
Operation frequency (seconds): 10 (not considered if randomly scheduled) Next Scheduled
Start Time: Start Time already passed
Group Scheduled : FALSE Randomly Scheduled : FALSE Life (seconds): Forever
Entry Ageout (seconds): never Recurring (Starting Everyday): FALSE
Status of entry (SNMP RowStatus): Active
Threshold (milliseconds): 5000 (not considered if react RTT is configured) Distribution
Statistics:
Number of statistic hours kept: 2
Number of statistic distribution buckets kept: 1
Statistic distribution interval (milliseconds): 20
History Statistics:
Number of history Lives kept: 0 Number of history Buckets kept: 15 History Filter Type:
None
Enhanced History:
The output lists the details of the configuration of operation 11. The operation is an ICMP
echo to [Link], with a frequency of 10 seconds, and it has already started (the start
time has already passed).
C] Issue the show ip sla statistics command to display the number of successes, failures,
and results of the latest operations.
Note: With Cisco IOS Release 12.4(4)T, 12.2(33)SB, and 12.2(33)SXI, the show ip sla
statistics
command has replaced the show ip sla monitor statistics command.
R1# show ip sla statistics
IPSLAs Latest Operation Statistics
IPSLA operation id: 11
Latest operation start time: *[Link].707 UTC Fri Apr 2 2010 Latest operation return code:
OK
D] Although not actually required because IP SLA session 11 alone could provide the
desired fault tolerance, create a second probe, 22, to test connectivity to the second DNS
server located on router ISP2. You can copy and paste the following commands on R1.
ip sla 22
icmp-echo [Link]
frequency 10 exit
ip sla schedule 22 life forever start-time now
E] Verify the new probe using the show ip sla configuration and show ip sla statistics
commands.
R1# show ip sla configuration 22 IP SLAs, Infrastructure Engine-II. Entry number: 22

Pillai HOC College of Art, Science and Commerce Page | 5


Modern Networking [Link] Sem-2

Owner:
Tag:
Type of operation to perform: icmp-echo
Target address/Source address: [Link]/[Link] Type Of Service parameter: 0x0
Request size (ARR data portion): 28 Operation timeout (milliseconds): 5000 Verify data: No
Vrf Name:
Schedule:
Operation frequency (seconds): 10 (not considered if randomly scheduled) Next Scheduled
Start Time: Start Time already passed
The output lists the details of the configuration of operation 22. The operation is an ICMP
echo to [Link], with a frequency of 10 seconds, and it has already started (the start
time has already passed). The statistics also prove that operation 22 is active.
Step 4: Configure tracking options.
Although PBR could be used, you will configure a floating static route that appears or
disappears depending on the success or failure of the IP SLA.
A] Remove the current default route on R1, and replace it with a floating static route
having an administrative distance of 5.
R1(config)# no ip route [Link] [Link] [Link]
R1(config)# ip route [Link] [Link] [Link] 5
R1(config)# exit
B] Verify the routing table.
R1# show ip route
*Apr 2 [Link].367: %SYS-5-CONFIG_I: Configured from console by console Codes: C -
connected, S - static, R - RIP, M - mobile, B - BGP
D - EIGRP, EX - EIGRP external, O - OSPF, IA - OSPF inter area
N1 - OSPF NSSA external type 1, N2 - OSPF NSSA external type 2
E1 - OSPF external type 1, E2 - OSPF external type 2
i - IS-IS, su - IS-IS summary, L1 - IS-IS level-1,
L2 - IS-IS level-2 ia - IS-IS inter area, * - candidate default, U - per-user static
Route
o - ODR, P - periodic downloaded static route
Gateway of last resort is [Link] to network [Link]
[Link]/30 is subnetted, 1 subnets
C [Link] is directly connected, Serial0/0/0 [Link]/30 is subnetted, 1 subnets
C [Link] is directly connected, Serial0/0/1C [Link]/24 is directly connected,
FastEthernet0/0 S* [Link]/0 [5/0] via [Link]
Notice that the default static route is now using the route with the administrative distance of
5. The first tracking object is tied to IP SLA object 11.
C] Use the track 1 ip sla 11 reachability command to enter the config-track
subconfiguration mode.
Note: With Cisco IOS Release 12.4(20)T, 12.2(33)SXI1, and 12.2(33)SRE and Cisco IOS
XE Release 2.4, the track ip sla command has replaced the track rtr command.
R1(config)# track 1 ip sla 11 reachability
R1(config-track)#
D] Specify the level of sensitivity to changes of tracked objects to 10 seconds of down
delay and 1 second of up delay using the delay down 10 up 1 command. The delay helps
to alleviate the effect of flapping objects—objects that are going down and up rapidly.
In this situation, if the DNS server fails momentarily and comes back up within 10
seconds, there is no impact.
R1(config-track)# delay down 10 up 1

Pillai HOC College of Art, Science and Commerce Page | 6


Modern Networking [Link] Sem-2

R1(config-track)# exit
R1(config)#
E] Configure the floating static route that will be implemented when tracking object 1 is
active. To view routing table changes as they happen, first enable the debug ip routing
command. Next, use the ip route [Link] [Link] [Link] 2 track 1 command to
create a floating static default route via [Link] (ISP1). Notice that this command
references the tracking object number 1, which in turn references IP SLA operation
number 11.
R1# debug ip routing
IP routing debugging is on R1#
*Apr 2 [Link].171: RT: NET-RED [Link]/0
R1# conf t
Enter configuration commands, one per line. End with CNTL/Z. R1(config)# ip route [Link]
[Link] [Link] 2 track 1 R1(config)#
*Apr 2 [Link].851: RT: closer admin distance for [Link], flushing 1
routes
*Apr 2 [Link].851: RT: NET-RED [Link]/0
*Apr 2 [Link].851: RT: add [Link]/0 via [Link], static metric
[2/0]
*Apr 2 [Link].851: RT: NET-RED [Link]/0
*Apr 2 [Link].851: RT: default path is now [Link] via [Link]
*Apr 2 [Link].855: RT: new default network [Link]
*Apr 2 [Link].855: RT: NET-RED [Link]/0
*Apr 2 [Link].851: RT: NET-RED [Link]/0
Notice that the default route with an administrative distance of 5 has been immediately
flushed because of a route with a better admin distance. It then adds the new default route
with the admin distance of 2.
F] Repeat the steps for operation 22, track number 2, and assign the static route an
admin distance higher than track 1 and lower than 5. On R1, copy the following
configuration, which sets an admin distance of 3.
track 2 ip sla 22 reachability
delay down 10 up 1 exit
ip route [Link] [Link] [Link] 3 track 2
G] Verify the routing table again.
R1# show ip route
Codes: C - connected, S - static, R - RIP, M - mobile, B - BGP
D - EIGRP, EX - EIGRP external, O - OSPF, IA - OSPF inter area
N1 - OSPF NSSA external type 1, N2 - OSPF NSSA external type 2
E1 - OSPF external type 1, E2 - OSPF external type 2i - IS-IS,
su - IS-IS summary, L1 - IS-IS level-1, L2 - IS-IS level-2ia –
IS-IS inter area, * - candidate default, U - per-user stati
o - ODR, P - periodic downloaded static route Gateway of last resort is [Link] to
network [Link]
[Link]/30 is subnetted, 1 subnets
C [Link] is directly connected, Serial0/0/0 [Link]/30 is subnetted, 1 subnets
C [Link] is directly connected, Serial0/0/1C192.168.1.0/24 is directly connected,
FastEthernet0/0 S* [Link]/0 [2/0] via [Link]
Although a new default route was entered, its administrative distance is not better than 2.
Therefore, itdoes not replace the previously entered default route.
Step 5: Verify IP SLA operation.

Pillai HOC College of Art, Science and Commerce Page | 7


Modern Networking [Link] Sem-2

In this step you observe and verify the dynamic operations and routing changes when tracked
objects [Link] following summarizes the process:
• Disable the DNS loopback interface on ISP1 (R2).
• Observe the output of the debug command on R1.
• Verify the static route entries in the routing table and the IP SLA statistics of R1.
• Re-enable the loopback interface on ISP1 (R2) and again observe the operation of the
IP SLAtracking feature.
ISP1(config)# interface loopback 1
ISP1(config-if)# shutdown ISP1(config-if)#
*Apr 2 [Link].307: %LINK-5-CHANGED: Interface Loopback1, changed state to
administratively down
*Apr 2 [Link].307: %LINEPROTO-5-UPDOWN: Line protocol on InterfaceLoopback1,
changed state to down
A] Shortly after the loopback interface is administratively down, observe the debug
output being generatedon R1.
R1#
*Apr 2 [Link].323: %TRACKING-5-STATE: 1 ip sla 11 reachability Up->Down
*Apr 2 [Link].323: RT: del [Link] via [Link], static metric [2/0]
*Apr 2 [Link].323: RT: delete network route to [Link]
*Apr 2 [Link].323: RT: NET-RED [Link]/0
*Apr 2 [Link].323: RT: NET-RED [Link]/0
*Apr 2 [Link].323: RT: add [Link]/0 via [Link], static metric
[3/0]
*Apr 2 [Link].323: RT: NET-RED [Link]/0
*Apr 2 [Link].323: RT: default path is now [Link] via [Link]
*Apr 2 [Link].323: RT: new default network [Link]
*Apr 2 [Link].327: RT: NET-RED [Link]/0
*Apr 2 [Link].171: RT: NET-RED [Link]/0
route
*Apr 2 [Link].327: %TRACKING-5-STATE: 1 ip sla 11 reachability Down->Up
*Apr 2 [Link].327: RT: closer admin distance for [Link], flushing 1 routes
*Apr 2 [Link].327: RT: NET-RED [Link]/0
*Apr 2 [Link].327: RT: add [Link]/0 via [Link], static metric [2/0]
*Apr 2 [Link].327: RT: NET-RED [Link]/0
*Apr 2 [Link].327: RT: default path is now [Link] via [Link]
*Apr 2 [Link].327: RT: new default network [Link]
*Apr 2 [Link].327: RT: NET-RED [Link]/0
*Apr 2 [Link].327: RT: NET-RED [Link]/0
*Apr 2 [Link].171: RT: NET-RED [Link]/0
Codes: C - connected, S - static, R - RIP, M - mobile, B - BGP
i - IS-IS, su - IS-IS summary, L1 - IS-IS level-1, L2 - IS-IS level-2ia - IS
IS inter area, * - candidate default, U - per- user static
o - ODR, P - periodic downloaded static route
Gateway of last resort is [Link] to network [Link]
[Link]/30 is subnetted, 1 subnets
C [Link] is directly connected, Serial0/0/0
[Link]/30 is subnetted, 1 subnets
C [Link] is directly connected, Serial0/0/1C
[Link]/24 is directly connected, FastEthernet0/0
S* [Link]/0 [2/0] via 209.165.201.

Pillai HOC College of Art, Science and Commerce Page | 8


Modern Networking [Link] Sem-2

PRACTICAL NO: 02
AIM: Using the AS_PATH Attribute
Topology

Objectives
Use BGP commands to prevent private AS numbers from being advertised to the outside
world.
Use the AS_PATH attribute to filter BGP routes based on their source AS numbers.
Background
The International Travel Agency’s ISP has been assigned an AS number of 300. This provider
uses BGP to exchange routing information with several customer networks. Each customer
network is assigned an AS number from the private range, such as AS 65000. Configure the
ISP router to remove the private AS numbers from the AS Path information of CustRtr.
Required Resources
3 routers (Cisco 1841 with Cisco IOS Release 12.4(24)T1 Advanced IP Services or
comparable)
Serial and console cables
Step 1: Prepare the routers for the lab.
Cable the network as shown in the topology diagram. Erase the startup configuration and
reload each router to clear previous configurations.
Step 2: Configure the hostname and interface addresses.
A] You can copy and paste the following configurations into your routers to begin.
Router R1 (hostname SanJose)
hostname SanJose
!
interface Loopback0
ip address [Link] [Link]
!
interface Serial0/0/0
ip address [Link] [Link]
clock rate 128000 no shutdown
Router R2 (hostname ISP)
hostname ISP
!
interface Loopback0
ip address [Link] [Link]
!

Pillai HOC College of Art, Science and Commerce Page | 9


Modern Networking [Link] Sem-2

interface Serial0/0/0
ip address [Link] [Link]
no shutdown
!
interface Serial0/0/1
ip address [Link] [Link]
clock rate 128000 no shutdown
Router R3 (hostname CustRtr)
hostname CustRtr
!
interface Loopback0
ip address [Link] [Link]
!
interface Serial0/0/1
ip address [Link] [Link]
no shutdown
B] Use ping to test the connectivity between the directly connected routers.
Note: SanJose will not be able to reach either ISP's loopback ([Link]) or CustRtr's loopback
([Link]), nor will it be able to reach either end of the link joining ISP to CustRtr
([Link] and [Link]).
Step 3: Configure BGP.
A] Configure BGP for normal operation. Enter the appropriate BGP commands on each
router so that they identify their BGP neighbors and advertise their loopback networks.
SanJose(config)# router bgp 100
SanJose(config-router)# neighbor [Link] remote-as 300
SanJose(config-router)# network [Link] mask [Link]
ISP(config)# router bgp 300
ISP(config-router)# neighbor [Link] remote-as 100
ISP(config-router)# neighbor [Link] remote-as 65000
ISP(config-router)# network [Link] mask [Link]
CustRtr(config)# router bgp 65000
CustRtr(config-router)# neighbor [Link] remote-as 300
CustRtr(config-router)# network [Link] mask [Link]
B] Verify that these routers have established the appropriate neighbor relationships by
issuing the show ipbgp neighbors command on each router.
ISP# show ip bgp neighbors
BGP neighbor is [Link], remote AS 65000, external link BGP version 4, remote router
ID [Link]
BGP state = Established, up for [Link]
<output omitted>
BGP neighbor is [Link], remote AS 100, external link BGP version 4, remote router ID
[Link]
BGP state = Established, up for [Link]
<output omitted>
Step 4: Remove the private AS.
A] Display the SanJose routing table using the show ip route command. SanJose should
have a route to both [Link] and [Link]. Troubleshoot if necessary.
SanJose# show ip route
Codes: C - connected, S - static, R - RIP, M - mobile, B - BGP
D - EIGRP, EX - EIGRP external, O - OSPF, IA - OSPF inter area

Pillai HOC College of Art, Science and Commerce Page | 10


Modern Networking [Link] Sem-2

B] Ping the [Link] address from [Link] does this fail?


C] Ping again, this time as an extended ping, sourcing from the Loopback0 interface
address.
SanJose# ping
Protocol [ip]:
Target IP address: [Link]
Repeat count [5]:
Datagram size [100]: Timeout in seconds [2]: Extended commands [n]: y
Source address or interface: [Link]
Type of service [0]:
Set DF bit in IP header? [no]:
!!!!!
Success rate is 100 percent (5/5), round-trip min/avg/max = 64/64/68 ms
Note: You can bypass extended ping mode and specify a source address using one of these
commands:
SanJose# ping [Link] source [Link]
or
SanJose# ping [Link] source Lo0
D] Check the BGP table from SanJose by using the show ip bgp command. Note the AS
path for the [Link] network. The AS 65000 should be listed in the path to [Link].
SanJose# show ip bgp
BGP table version is 5, local router ID is [Link]
Status codes: s suppressed, d damped, h history, * valid, > best, i – internal Origin codes: i -
IGP, e - EGP, ? - incomplete
Network Next Hop Metric LocPrf Weight Path
*> [Link] [Link] 32768 i
*> [Link] [Link] 0 300 i
*> [Link] [Link] 0 300 65000 i
E] Configure ISP to strip the private AS numbers from BGP routes exchanged with
SanJose using the following commands.
ISP(config)# router bgp 300
ISP(config-router)# neighbor [Link] remove-private-as
F] After issuing these commands, use the clear ip bgp * command on ISP to reestablish
the BGP relationship between the three routers. Wait several seconds and then return to
SanJose to check its routing table.
Note: The clear ip bgp * soft command can also be used to force each router to resend its
BGP table. Does SanJose still have a route to [Link]?
SanJose should be able to ping [Link] using its loopback 0 interface as the source of the
ping.
SanJose# ping [Link] source lo0
Type escape sequence to abort.
Sending 5, 100-byte ICMP Echos to [Link], timeout is 2 seconds:
Packet sent with a source address of [Link] !!!
Success rate is 100 percent (5/5), round-trip min/avg/max = 28/28/32 ms
Now check the BGP table on SanJose. The AS_ PATH to the [Link] network should be AS
300. It no longer has the private AS in the path.
Network Next Hop Metric LocPrf Weight Path
*> [Link] [Link] 32768 i
*> [Link] [Link] 0 300 i
*> [Link] [Link] 0 300 i

Pillai HOC College of Art, Science and Commerce Page | 11


Modern Networking [Link] Sem-2

Step 5: Use the AS_PATH attribute to filter routes.


As a final configuration, use the AS_PATH attribute to filter routes based on their origin. In a
complex environment, you can use this attribute to enforce routing policy. In this case, the
provider router, ISP, must be configured so that it does not propagate routes that originate
from AS 100 to the customer router CustRtr.
AS-path access lists are read like regular access lists. The statements are read sequentially,
and there is an implicit deny at the end. Rather than matching an address in each statement
like a conventional access list, AS path access lists match on something called a regular
expression. Regular expressions are a way of matching text patterns and have many uses. In
this case, you will be using them in the AS path access list to match text patterns in AS paths.
A] Configure a special kind of access list to match BGP routes with an AS_PATH
attribute that both begins and ends with the number 100. Enter the following
commands on ISP.
For more details on configuring regular expressions on Cisco routers, see:
[Link]
SD_Products
_Configuration_Guide_Chapter.html
B] Apply the configured access list using the neighbor command with the filter-list
option.
ISP(config)# router bgp 300
ISP(config-router)# neighbor [Link] filter-list 1 out
The out keyword specifies that the list is applied to routing information sent to this neighbor.
Use the clear ip bgp * command to reset the routing information. Wait several seconds and
then check the routing table for ISP. The route to [Link] should be in the routing table.
Note: To force the local router to resend its BGP table, a less disruptive option is to use the
clear ip bgp
C] Run the following Tcl script on all routers to verify whether there is connectivity. All
pings from ISP should be successful. SanJose should not be able to ping the CustRtr
loopback [Link] or the WAN link
[Link]/30. CustRtr should not be able to ping the SanJose loopback [Link] or the
WAN link [Link]/30.
ISP# tclsh
foreach address { [Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
}{
ping $address }

Pillai HOC College of Art, Science and Commerce Page | 12


Modern Networking [Link] Sem-2

PRACTICAL NO: 03
AIM: Configuring IBGP and EBGP Sessions, Local Preference, and MED
Topology

Objectives
• For IBGP peers to correctly exchange routing information, use the next-hop-self
command with the Local- Preference and MED attributes.
• Ensure that the flat-rate, unlimited-use T1 link is used for sending and receiving data
to and from the AS 200 on ISP and that the metered T1 only be used in the event that
the primary T1 link has failed.
Background
The International Travel Agency runs BGP on its SanJose1 and SanJose2 routers externally
with the ISP router in AS 200. IBGP is run internally between SanJose1 and SanJose2. Your
job is to configure both EBGP and IBGP for this internetwork to allow for redundancy. The
metered T1 should only be used in the event that the primary T1 link has failed. Traffic sent
across the metered T1 link offers the same bandwidth of the primary link but at a huge
expense. Ensure that this link is not used unnecessarily.
Note: This lab uses Cisco 1941 routers with Cisco IOS Release 15.4 with IP Base. The
switches are Cisco WS-C2960-24TT-L with Fast Ethernet interfaces, therefore the router will
use routing metrics associated with a 100 Mb/s interface. Depending on the router or switch
model and Cisco IOS Software version, the commands available and output produced might
vary from what is shown in this lab.
Required Resources
• 3 routers (Cisco IOS Release 15.2 or comparable)
• Serial and Ethernet cables
Step 0: Suggested starting configurations.
A] Apply the following configuration to each router along with the appropriate
hostname. The exec-timeout 0 0 command should only be used in a lab environment.
Router(config)# no ip domain-lookup
Router(config)# line con 0 Router(config-line)# logging synchronous Router(config-line)#
exec-timeout 0 0
Step 1: Configure interface addresses.

Pillai HOC College of Art, Science and Commerce Page | 13


Modern Networking [Link] Sem-2

A] Using the addressing scheme in the diagram, create the loopback interfaces and
apply IPv4 addresses to these and the serial interfaces on ISP (R1), SanJose1 (R2), and
SanJose2 (R3).
Router R1 (hostname ISP)
ISP(config)# interface Loopback0
ISP(config-if)# ip address [Link] [Link]
ISP(config-if)# exit
ISP(config)# interface Serial0/0/0
ISP(config-if)# ip address [Link] [Link]
ISP(config-if)# clock rate 128000 ISP(config-if)# no shutdown ISP(config-if)# exit
ISP(config)# interface Serial0/0/1
ISP(config-if)# ip address [Link] [Link]
ISP(config-if)# no shutdown
ISP(config-if)# end
ISP#
Router R2 (hostname SanJose1)
SanJose1(config)# interface Loopback0
SanJose1(config-if)# ip address [Link] [Link]
SanJose1(config-if)# exit
SanJose1(config)# interface Serial0/0/0
SanJose1(config-if)# ip address [Link] [Link]
SanJose1(config-if)# no shutdown SanJose1(config-if)# exit SanJose1(config)# interface
Serial0/0/1
SanJose1(config-if)# ip address [Link] [Link]
SanJose1(config-if)# clock rate 128000 SanJose1(config-if)# no shutdown SanJose1(config-
if)# end
SanJose1#
Router R3 (hostname SanJose2)
SanJose2(config)# interface Loopback0
SanJose2(config-if)# ip address [Link] [Link]
SanJose2(config-if)# exit
SanJose2(config)# interface Serial0/0/0
SanJose2(config-if)# ip address [Link] [Link]
SanJose2(config-if)# clock rate 128000 SanJose2(config-if)# no shutdown SanJose2(config-
if)# exit SanJose2(config)# interface Serial0/0/1
SanJose2(config-if)# ip address [Link] [Link]
SanJose2(config-if)# no shutdown
SanJose2(config-if)# end
SanJose2#
B] Use ping to test the connectivity between the directly connected routers. Both
SanJose routers should be able to ping each other and their local ISP serial link IP
address. The ISP router cannot reach the segment between SanJose1 and SanJose2.
Step 2: Configure EIGRP.
Configure EIGRP between the SanJose1 and SanJose2 routers. (Note: If using an IOS prior to
15.0, use the no auto-summary router configuration command to disable automatic
summarization. This command is the default beginning with IOS 15.)
SanJose1(config)# router eigrp 1
SanJose1(config-router)# network [Link]
SanJose2(config)# router eigrp 1
SanJose2(config-router)# network [Link]

Pillai HOC College of Art, Science and Commerce Page | 14


Modern Networking [Link] Sem-2

Step 3: Configure IBGP and verify BGP neighbors.


A] Configure IBGP between the SanJose1 and SanJose2 routers. On the SanJose1
router, enter the following configuration.
SanJose1(config)# router bgp 64512
SanJose1(config-router)# neighbor [Link] remote-as 64512
SanJose1(config-router)# neighbor [Link] update-source lo0
If multiple pathways to the BGP neighbor exist, the router can use multiple IP interfaces to
communicate with the neighbor. The source IP address therefore depends on the outgoing
interface. The update-source lo0 command instructs the router to use the IP address of the
interface Loopback0 as the source IP address for all BGP messages sent to that neighbor.
B] Complete the IBGP configuration on SanJose2 using the following commands.
SanJose2(config)# router bgp 64512
SanJose2(config-router)# neighbor [Link] remote-as 64512
SanJose2(config-router)# neighbor [Link] update-source lo0
C] Verify that SanJose1 and SanJose2 become BGP neighbors by issuing the show ip
bgp neighbors command on SanJose1. View the following partial output. If the BGP
state is not established, troubleshoot the connection.
SanJose2# show ip bgp neighbors
BGP neighbor is [Link], remote AS 64512, internal link BGP version 4, remote router
ID [Link]
Step 4: Configure EBGP and verify BGP neighbors.
A] Configure ISP to run EBGP with SanJose1 and SanJose2. Enter the following
commands on ISP.
ISP(config)# router bgp 200
ISP(config-router)# neighbor [Link] remote-as 64512
ISP(config-router)# neighbor [Link] remote-as 64512
ISP(config-router)# network [Link]
B] Configure a discard static route for the [Link]/16 network. Any packets that do
not have a more specific match (longer match) for a [Link] subnet will be dropped
instead of sent to the ISP. Later in this lab we will configure a default route to the ISP.
SanJose1(config)# ip route [Link] [Link] null0
C] Configure SanJose1 as an EBGP peer to ISP.
SanJose1(config)# router bgp 64512
SanJose1(config-router)# neighbor [Link] remote-as 200
SanJose1(config-router)# network [Link]
D] Use the show ip bgp neighbors command to verify that SanJose1 and ISP have
reached the established state. Troubleshoot if necessary.
SanJose1# show ip bgp neighbors
BGP neighbor is [Link], remote AS 64512, internal link BGP version 4, remote router
ID [Link]
BGP state = Established, up for [Link]
<output omitted>
BGP neighbor is [Link], remote AS 200, external link BGP version 4, remote router ID
[Link]
BGP state = Established, up for [Link]
.
*Sep 8 [Link].699: %BGP-5-ADJCHANGE: neighbor [Link] Up
E] Configure a discard static route for [Link]/16 on SanJose2 and as an EBGP peer
to ISP.
SanJose2(config)# ip route [Link] [Link] null0

Pillai HOC College of Art, Science and Commerce Page | 15


Modern Networking [Link] Sem-2

SanJose2(config)# router bgp 64512


SanJose2(config-router)# neighbor [Link] remote-as 200
SanJose2(config-router)# network [Link]
Step 5: View BGP summary output.
In Step 4, the show ip bgp neighbors command was used to verify that SanJose1 and
ISP had reached the established state. A useful alternative command is show ip bgp
summary. The output should be similar to the following.
SanJose2# show ip bgp summary
BGP router identifier [Link], local AS number 64512 BGP table version is 6, main
routing table version 6
2 network entries using 288 bytes of memory
4 path entries using 320 bytes of memory
4/2 BGP path/bestpath attribute entries using 640 bytes of memory
1 BGP AS-PATH entries using 24 bytes of memory
0 BGP route-map cache entries using 0 bytes of memory
0 BGP filter-list cache entries using 0 bytes of memory BGP using 1272 total bytes of
memory
GP activity 2/0 prefixes, 4/0 paths, scan interval 60 secs
Status codes: s suppressed, d damped, h history, * valid, > best, i - internal, r RIB-failure, S
Stale, m multipath, b backup-path, f RT-Filter, x best-external, a additional-path, c RIB-
compressed,
Origin codes: i - IGP, e - EGP, ? - incomplete
RPKI validation codes: V valid, I invalid, N Not found
Network Next Hop Metric LocPrf Weight Path
* i [Link] [Link] 0 100 0i
*> [Link] 0 32768 i
*> [Link] [Link] 0 150 0 200 i
SanJose1#
SanJose2# show ip bgp
BGP table version is 7, local router ID is [Link]
Status codes: s suppressed, d damped, h history, * valid, > best, i - internal, r RIB-failure, S
Stale, m multipath, b backup-path, f RT-Filter, x best-external, a additional-path, c RIB-
compressed,
Origin codes: i - IGP, e - EGP, ? - incomplete
RPKI validation codes: V valid, I invalid, N Not found
Network Next Hop Metric LocPrf Weight Path
*i [Link] [Link] 0 100 0i
*> [Link] 0 32768 i
*>i 192.168.100. [Link] 0 150 0 200 i
0
* [Link] 0 125 0 200 i
SanJose2#
This now indicates that routing to the loopback segment for ISP [Link] /24 can be
reached only through the link common to SanJose1 and ISP. SanJose2’s next hop to
[Link]/24 is SanJose1 because both routers have been configured using the next-hop-
self command.
Step 9: Set BGP MED.
a. In the previous step we saw that SanJose1 and SanJose2 will route traffic for
[Link]/24 using the link between SanJose1 and ISP. Examine what the return path ISP

Pillai HOC College of Art, Science and Commerce Page | 16


Modern Networking [Link] Sem-2

takes to reach AS 64512. Notice that the return path is different from the original path. This is
known as asymmetric routing and is not necessarily an unwanted trait.
ISP# show ip bgp
BGP table version is 22, local router ID is [Link]
Status codes: s suppressed, d damped, h history, * valid, > best, i - internal, r RIB-failure, S
Stale, m multipath, b backup-path, f RT-Filter, x best-external, a additional-path, c RIB-
compressed
Set DF bit in IP header? [no]:
([Link])
([Link])
Reply to request 0 (28 ms). Received packet has options Total option bytes= 40, padded
length=40
Record route: ([Link])
([Link])
([Link])
([Link])
([Link])
([Link]) <*>
([Link])
([Link])
([Link])
End of list
Reply to request 1 (28 ms). Received packet has options Total option bytes= 40, padded
length=40
Record route: ([Link])
([Link])
([Link])
([Link]) <*>
([Link])
([Link])
([Link])
End of list
Reply to request 2 (28 ms). Received packet has options Total option bytes= 40, padded
length=40
Record route: ([Link])
([Link])
([Link])
([Link])
([Link])
([Link])
([Link])
([Link])
End of list
Reply to request 3 (28 ms). Received packet has options Total option bytes= 40, padded
length=40
Record route: ([Link])
([Link])
([Link])
([Link])
([Link])

Pillai HOC College of Art, Science and Commerce Page | 17


Modern Networking [Link] Sem-2

([Link]) <*>
([Link])
([Link])
([Link])
End of list
Reply to request 4 (28 ms). Received packet has options Total option bytes= 40, padded
length=40
Record route: ([Link])
([Link])
([Link])
([Link])
([Link])
([Link]) <*>
([Link])
([Link])
([Link])
End of list
Success rate is 100 percent (5/5), round-trip min/avg/max = 28/28/28 ms SanJose2#
Step 10: Establish a default [Link] final step is to establish a default route that uses a
policy statement that adjusts to changes in the network.
Configure ISP to inject a default route to both SanJose1 and SanJose2 using BGP using the
default- originate command. This command does not require the presence of [Link] in the
ISP router. Configure the [Link]/8 network which will not be advertised using BGP. This
network will be used to test the default route on SanJose1 and SanJose2.
ISP(config)# router bgp 200
ISP(config-router)# neighbor [Link] default-originate ISP(config-router)# neighbor
[Link] default-originate ISP(config-router)# exit
ISP(config)# interface loopback 10
ISP(config-if)# ip address [Link] [Link]
ISP(config-if)#
a - application route
+ - replicated route, % - next hop override Gateway of last resort is [Link] to network
[Link]
B* [Link]/0 [20/0] via [Link], [Link]
EIGRP external, O - OSPF, IA - OSPF inter area
N1 - OSPF NSSA external type 1, N2 - OSPF NSSA external type 2 E1 - OSPF external type
1, E2 - OSPF external type 2
B* [Link]/0 [200/0] via [Link], [Link]
[Link]/16 is variably subnetted, 6 subnets, 3 masks S [Link]/16 is directly
connected, Null0
[Link]/24 is directly connected, Serial0/0/1 L [Link]/32 is directly connected,
Serial0/0/1
[Link]/24 [90/2297856] via [Link], [Link], Serial0/0/1
C [Link]/24 is directly connected, Loopback0 L [Link]/32 is directly
connected, Loopback0 B [Link]/24 [200/0] via [Link], [Link]
SanJose1#
SanJose2# show ip route
Codes: L - local, C - connected, S - static, R - RIP, M - mobile, B - BGP D - EIGRP, EX -
EIGRP external, O - OSPF, IA - OSPF inter area

Pillai HOC College of Art, Science and Commerce Page | 18


Modern Networking [Link] Sem-2

PRACTICAL NO: 04
AIM: Secure the Management Plane
Topology

Objectives
• Secure management access.
• Configure enhanced username password security.
• Enable AAA RADIUS authentication.
• Enable secure remote management.
Background
The management plane of any infrastructure device should be protected as much as possible.
Controlling access to routers and enabling reporting on routers are critical to network security
and should be part of a comprehensive security policy.
In this lab, you build a multi-router network and secure the management plane of routers R1
and R3.
Note: This lab uses Cisco 1941 routers with Cisco IOS Release 15.2 with IP Base. Depending
on the router or switch model and Cisco IOS Software version, the commands available and
output produced might vary from what is shown in this lab.
Required Resources
• 3 routers (Cisco IOS Release 15.2 or comparable)
• Serial and Ethernet cables
Step 1: Configure loopbacks and assign addresses.
Cable the network as shown in the topology diagram. Erase the startup configuration and
reload each router to clear previous configurations. Using the addressing scheme in the
diagram, apply the IP addresses to the interfaces on the R1, R2, and R3 routers.
You can copy and paste the following configurations into your routers to begin.
Note: Depending on the router model, interfaces might be numbered differently than those
listed. You might need to alter the designations accordingly.
R1
hostname R1
interface Loopback 0 description R1 LAN
ip address [Link] [Link]
exit

Pillai HOC College of Art, Science and Commerce Page | 19


Modern Networking [Link] Sem-2

!
interface Serial0/0/0 description R1 --> R2
ip address [Link] [Link]
clock rate 128000 no shutdown
exit
!
end
R2
hostname R2
!
interface Serial0/0/0 description R2 --> R1
ip address [Link] [Link]
no shutdown exit
interface Serial0/0/1 description R2 --> R3
ip address [Link] [Link]
clock rate 128000 no shutdown
exit
!
end
R3
hostname R3
!
interface Loopback0 description R3 LAN
ip address [Link] [Link]
exit
Step 2: Configure static routes.
On R1, configure a default static route to ISP.
R1(config)# ip route [Link] [Link] [Link]
On R3, configure a default static route to ISP.
R3(config)# ip route [Link] [Link] [Link]
On R2, configure two static routes.
i. R2(config)# ip route [Link] [Link] [Link]
ii. R2(config)# ip route [Link] [Link] [Link]
From the R1 router, run the following Tcl script to verify connectivity.
foreach address { [Link]
[Link]
[Link]
[Link]
[Link]
[Link]
} { ping $address }
R1# tclsh
R1(tcl)#foreach address {
+>(tcl)#[Link]
+>(tcl)#[Link]
+>(tcl)#[Link]
+>(tcl)#[Link]
+>(tcl)#[Link]
+>(tcl)#[Link]
+>(tcl)#} { ping $address }

Pillai HOC College of Art, Science and Commerce Page | 20


Modern Networking [Link] Sem-2

Success rate is 100 percent (5/5), round-trip min/avg/max = 1/1/1 ms Type escape sequence
to abort.
Sending 5, 100-byte ICMP Echos to [Link], timeout is 2 seconds:
!!!!!
Success rate is 100 percent (5/5), round-trip min/avg/max = 1/2/4 ms Type escape sequence
to abort.
Sending 5, 100-byte ICMP Echos to [Link], timeout is 2 seconds:
!!!!!
Success rate is 100 percent (5/5), round-trip min/avg/max = 1/1/4 ms Type escape sequence
to abort.
Sending 5, 100-byte ICMP Echos to [Link], timeout is 2 seconds:
!!!!!
Success rate is 100 percent (5/5), round-trip min/avg/max = 1/1/4 ms Type escape sequence
to abort.
Sending 5, 100-byte ICMP Echos to [Link], timeout is 2 seconds:
!!!!!
Success rate is 100 percent (5/5), round-trip min/avg/max = 12/14/16 ms Type escape
sequence to abort.
Sending 5, 100-byte ICMP Echos to [Link], timeout is 2 seconds:
!!!!!
Success rate is 100 percent (5/5), round-trip min/avg/max = 12/15/16 ms R1(tcl)#
Are the pings now successful?
Configure a console password and enable login for routers. For additional security, the exec-
timeout command causes the line to log out after 5 minutes of inactivity. The logging
synchronous command prevents console messages from interrupting command entry.
Note: To avoid repetitive logins during this lab, the exec-timeout command can be set to 0 0,
R1(config-line)# password ciscovtypass R1(config-line)# exec-timeout 5 0 R1(config-line)#
To increase the encryption level of console and VTY lines, it is recommended to enable
authentication using the local database. The local database consists of usernames and
password combinations that are created locally on each device. The local and VTY lines are
configured to refer to the local database when authenticating a user.
To create local database entry encrypted to level 4 (SHA256), use the username name secret
password
global configuration command. In global configuration mode, enter the following command:
R1(config)# username JR-ADMIN secret class12345
R1(config)# username ADMIN secret class54321
Set the console line to use the locally defined login accounts.
R1(config)# line console 0 R1(config-line)# login local R1(config-line)# exit R1(config)#
Set the vty lines to use the locally defined login accounts.
R1(config)# line vty 0 4 R1(config-line)# login local R1(config-line)# end R1(config)#
Repeat the steps 4a to 4c on R3. i.
To verify the configuration, telnet to R3 from R1 and login using the ADMIN local database
account.
R1# telnet [Link]
Trying [Link] ... Open
Username: ADMIN
Password:
R3>

Pillai HOC College of Art, Science and Commerce Page | 21


Modern Networking [Link] Sem-2

PRACTICAL NO: 05
AIM: Configure and Verify Path ControL
Topology

Objectives
• Configure and verify policy-based routing.
• Select the required tools and commands to configure policy-based routing operations.
• Verify the configuration and operation by using the proper show and debug
commands.
Background
You want to experiment with policy-based routing (PBR) to see how it is implemented and to
study how it could be of value to your organization. To this end, you have interconnected and
configured a test network with four routers. All routers are exchanging routing information
using EIGRP.
Note: This lab uses Cisco 1841 routers with Cisco IOS Release 12.4(24)T1, and the
Advanced IP Services image [Link]. You can use other
routers (such as 2801 or 2811) and Cisco IOS Software versions if they have comparable
capabilities and features. Depending on the router and software version, the commands
available and output produced might vary from what is shown in this lab.
Required Resources
• 4 routers (Cisco 1841 with Cisco IOS Release 12.4(24)T1 Advanced IP Services or
comparable)
• Serial and console cables
Step 1: Prepare the routers for the lab.
Cable the network as shown in the topology diagram. Erase the startup configuration, and
reload each router to clear previous configurations.
Step 2: Configure router hostname and interface addresses.
Using the addressing scheme in the diagram, create the loopback interfaces and apply IP
addresses to these and the serial interfaces on R1, R2, R3, and R4. On the serial interfaces
connecting R1 to R3 and R3 to R4, specify the bandwidth as 64 Kb/s and set a clock rate on
the DCE using the clock rate 64000 command. On the serial interfaces connecting R1 to R2
and R2 to R3, specify the bandwidth as 128 Kb/s and set a clock rate on the DCE using the
clock rate 128000 command.
You can copy and paste the following configurations into your routers to begin.

Pillai HOC College of Art, Science and Commerce Page | 22


Modern Networking [Link] Sem-2

Note: Depending on the router model, interfaces might be numbered differently than those
listed. You might need to alter them accordingly.
Router R1
hostname R1
!
interface Lo1 description R1 LAN
ip address [Link] [Link]
!
interface Serial0/0/0 description R1 --> R2
ip address [Link] [Link]
clock rate 128000 bandwidth 128no shutdown
!
interface Serial0/0/1 description R1 --> R3
ip address [Link] [Link]
bandwidth 64no shutdown
!
end
Router R2
hostname R2
!
interface Lo2 description R2 LAN
ip address [Link] [Link]
!
interface Serial0/0/0 description R2 --> R1
ip address [Link] [Link]
bandwidth 128no shutdown
interface Serial0/0/1 description R2 --> R3
ip address [Link] [Link]
clock rate 128000
Router R2
router eigrp 1
network [Link]
network [Link] [Link]
network [Link] [Link]
no auto-summary
Router R3
router eigrp 1
network [Link]
network [Link] [Link]
network [Link] [Link]
network [Link] [Link]
no auto-summary
Router R4
router eigrp 1
network [Link]
network [Link] [Link]
no auto-summary
You should see EIGRP neighbor relationship messages being generated.
foreach address { [Link]
[Link]

Pillai HOC College of Art, Science and Commerce Page | 23


Modern Networking [Link] Sem-2

[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
} { ping $address }
You should get ICMP echo replies for every address pinged. Make sure to run the Tcl script
on each router.
Step 5: Verify the current path.
Before you configure PBR, verify the routing table on R1.
On R1, use the show ip route command. Notice the next-hop IP address for all networks
discovered by EIGRP.
R1# show ip route
Codes: C - connected, S - static, R - RIP, M - mobile, B - BGP
D - EIGRP, EX - EIGRP external, O - OSPF, IA - OSPF inter areaN1 - OSPF NSSA
external type 1, N2 - OSPF NSSA external type 2E1 - OSPF external type 1, E2 -
OSPF external type 2
i - IS-IS, su - IS-IS summary, L1 - IS-IS level-1, L2 - IS-IS level-2ia - IS-IS inter area, * -
candidate default, U - per-user static
route
o - ODR, P - periodic downloaded static route
Gateway of last resort is not set [Link]/29 is subnetted, 4 subnets
D [Link] [90/41024000] via [Link], [Link], Serial0/0/1D
[Link]
[90/21024000] via [Link], [Link], Serial0/0/0
[Link] is directly connected, Serial0/0/0C [Link] is directly connected, Serial0/0/1
[Link]/25 is subnetted, 2 subnets
[Link] [90/41152000] via [Link], [Link], Serial0/0/1 D [Link]
[90/41152000] via [Link], [Link], Serial0/0/1
[Link]/24 is directly connected, Loopback1
[Link]/24 [90/20640000] via [Link], [Link], Serial0/0/0D [Link]/24
[90/21152000] via [Link], [Link], Serial0/0/0
*Feb 23 [Link].467: IP: s=[Link] (Serial0/1/0), d=[Link] (Se
rial0/0/0), len 28, policy routed
*Feb 23 [Link].467: IP: Serial0/1/0 to Serial0/0/0 [Link]
*Feb 23 [Link].471: IP: s=[Link] (Serial0/1/0), d=[Link], le
n 28, policy match
*Feb 23 [Link].471: IP: route map R3-to-R1, item 10, permit
*Feb 23 [Link].471: IP: s=[Link] (Serial0/1/0), d=[Link] (Se
rial0/0/0), len 28, policy routed
*Feb 23 [Link].471: IP: Serial0/1/0 to Serial0/0/0 [Link]
*Feb 23 [Link].471: IP: s=[Link] (Serial0/1/0), d=[Link], le
n 28, policy match
*Feb 23 [Link].471: IP: route map R3-to-R1, item 10, permit

Pillai HOC College of Art, Science and Commerce Page | 24


Modern Networking [Link] Sem-2

*Feb 23 [Link].475: IP: s=[Link] (Serial0/1/0), d=[Link] (Se


rial0/0/0), len 28, policy routed
*Feb 23 [Link].475: IP: Serial0/1/0 to Serial0/0/0 [Link]
*Feb 23 [Link].475: IP: s=[Link] (Serial0/1/0), d=[Link], le
n 28, FIB policy match
*Feb 23 [Link].475: IP: s=[Link] (Serial0/1/0), d=[Link], g=
[Link], len 28, FIB policy routed
*Feb 23 [Link].483: IP: s=[Link] (Serial0/1/0), d=[Link], le
n 28, FIB policy match
*Feb 23 [Link].483: IP: s=[Link] (Serial0/1/0), d=[Link], g=
[Link], len 28, FIB policy routed
*Feb 23 [Link].491: IP: s=[Link] (Serial0/1/0), d=[Link], le
n 28, FIB policy match
*Feb 23 [Link].491: IP: s=[Link] (Serial0/1/0), d=[Link], g=
[Link], len 28, FIB policy routed
On R3, display the policy and matches using the show route-map command.
R3# show route-map
route-map R3-to-R1, permit, sequence 10 Match clauses:
ip address (access-lists): PBR- ACLSet clauses:
ip next-hop [Link]
Policy routing matches: 12 packets, 384 bytes
Note: There are now matches to the

Pillai HOC College of Art, Science and Commerce Page | 25


Modern Networking [Link] Sem-2

PRACTICAL NO: 06
AIM: Configure IP SLA Tracking and Path Control with gateway
Topology

Objectives
• Configure and verify the IP SLA feature.
• Test the IP SLA tracking feature.
• Verify the configuration and operation using show and debug commands.
Background
You want to experiment with the Cisco IP Service Level Agreement (SLA) feature to study
how it could be of value to your organization.
At times, a link to an ISP could be operational, yet users cannot connect to any other outside
Internet resources. The problem might be with the ISP or downstream from them. Although
policy-based routing (PBR) can be implemented to alter path control, you will implement the
Cisco IOS SLA feature to monitor this behavior and intervene by injecting another default
route to a backup ISP.
Required Resources
• 3 routers (Cisco IOS Release 15.2 or comparable)
• Serial and Ethernet cables
Step 1: Configure loopbacks and assign addresses.
Cable the network as shown in the topology diagram. Erase the startup configuration and
reload each router to clear the previous configurations. Using the addressing scheme in the
diagram, create the loopback interfaces and apply IP addresses to them as well as the serial
interfaces on R1, ISP1, and ISP2.
You can copy and paste the following configurations into your routers to begin.
Note: Depending on the router model, interfaces might be numbered differently than those
listed. You might need to alter them accordingly.
Router R1
hostname R1
interface Loopback 0 description R1 LAN

Pillai HOC College of Art, Science and Commerce Page | 26


Modern Networking [Link] Sem-2

ip address [Link] [Link]


interface Serial0/0/0 description R1 --> ISP1
ip address [Link] [Link]
clock rate 128000
bandwidth 128 no shutdown
interface Serial0/0/1 description R1 --> ISP2
ip address [Link] [Link]
bandwidth 128 no shutdown
Router ISP1 (R2)
hostname ISP1
interface Loopback0
description Simulated Internet Web Server ip address [Link] [Link]
interface Loopback1 description ISP1 DNS Server
ip address [Link] [Link]
interface Serial0/0/0 description ISP1 --> R1
ip address [Link] [Link]
bandwidth 128 no shutdown
interface Serial0/0/1 description ISP1 --> ISP2
ip address [Link] [Link]
clock rate 128000
Router ISP2 (R3)
hostname ISP2 interface Loopback0
description Simulated Internet Web Server ip address [Link] [Link]
interface Loopback1 description ISP2 DNS Server
ip address [Link] [Link]
interface Serial0/0/0 description ISP2 --> R1
ip address [Link] [Link]
clock rate 128000
bandwidth 128 no shutdown
interface Serial0/0/1 description ISP2 --> ISP1
ip address [Link] [Link]
bandwidth 128 no shutdown
Verify the configuration by using the show interfaces description command. The output from
router R1 is shown here as an example.
R1# show interfaces description | include up
Se0/0/0 up up R1 --> ISP1
Se0/0/1 up up R1 --> ISP2
Lo0 up up R1 LAN
R1#
All three interfaces should be active. Troubleshoot if necessary.
Step 2: Configure static routing.
The current routing policy in the topology is as follows:
Router R1 establishes connectivity to the Internet through ISP1 using a default static route.
ISP1 and ISP2 have dynamic routing enabled between them, advertising their respective
public address pools.
ISP1 and ISP2 both have static routes back to the ISP LAN.
Note: For the purpose of this lab, the ISPs have a static route to an RFC 1918 private network
address on the branch router R1. In an actual branch implementation, Network Address
Translation (NAT) would be configured for all traffic exiting the branch LAN. Therefore, the

Pillai HOC College of Art, Science and Commerce Page | 27


Modern Networking [Link] Sem-2

static routes on the ISP routers would be pointing to the provided public pool of the branch
office.
Implement the routing policies on the respective routers. You can copy and paste the
following configurations.
Router R1
R1(config)# ip route [Link] [Link] [Link]
R1(config)#
Router ISP1 (R2)
ISP1(config)# router eigrp 1
ISP1(config-router)# network [Link] [Link]
ISP1(config-router)# network [Link] [Link]
ISP1(config-router)# no auto-summary ISP1(config-router)# exit ISP1(config)#
ISP1(config-router)# ip route [Link] [Link] [Link]
ISP1(config)#
Router ISP2 (R3)
ISP2(config)# router eigrp 1
ISP2(config-router)# network [Link] [Link]
ISP2(config-router)# network [Link] [Link]
ISP2(config-router)# no auto-summary ISP2(config-router)# exit ISP2(config)#
ISP2(config)# ip route [Link] [Link] [Link]
ISP2(config)#
EIGRP neighbor relationship messages on ISP1 and ISP2 should be generated. Troubleshoot
if necessary.
The Cisco IOS IP SLA feature enables an administrator to monitor network performance
between Cisco devices (switches or routers) or from a Cisco device to a remote IP device. IP
SLA probes continuously check the reachability of a specific destination, such as a provider
edge router interface, the DNS server of the ISP, or any other specific destination, and can
conditionally announce a default route only if the connectivity is verified.
Before implementing the Cisco IOS SLA feature, you must verify reachability to the Internet
servers. From router R1, ping the web server, ISP1 DNS server, and ISP2 DNS server to
verify connectivity. You can copy the following Tcl script and paste it into R1.
foreach address { [Link]
[Link]
[Link] } {
ping $address source [Link] }
All pings should be successful. Troubleshoot if necessary.
Trace the path taken to the web server, ISP1 DNS server, and ISP2 DNS server. You can copy
the following Tcl script and paste it into R1.
foreach address { [Link]
[Link]
[Link] } {
trace $address source [Link] }
Through which ISP is traffic flowing?
R1# show ip sla configuration 22 IP SLAs, Infrastructure Engine-II. Entry number: 22
Owner:
Tag:
Type of operation to perform: icmp-echo
Target address/Source address: [Link]/[Link] Type Of Service parameter: 0x0
Request size (ARR data portion): 28 Operation timeout (milliseconds): 5000 Verify data: No
Vrf Name:

Pillai HOC College of Art, Science and Commerce Page | 28


Modern Networking [Link] Sem-2

Schedule:
Operation frequency (seconds): 10 (not considered if randomly scheduled)
Next Scheduled Start Time: Start Time already passed Group Scheduled : FALSE
Randomly Scheduled : FALSE Life (seconds): Forever Entry Ageout (seconds): never
Recurring (Starting Everyday): FALSE Status of entry (SNMP RowStatus): Active
Threshold (milliseconds): 5000 (not considered if react RTT is configured)
Distribution Statistics:
Number of statistic hours kept: 2
Number of statistic distribution buckets kept: 1 Statistic distribution interval (milliseconds):
20
History Statistics:
Number of history Lives kept: 0 Number of history Buckets kept: 15 History Filter Type:
None
Enhanced History:
R1#
R1# show ip sla statistics 22
IPSLAs Latest Operation Statistics
IPSLA operation id: 22
Latest RTT: 16 milliseconds
Latest operation start time: [Link] UTC Sat Jan 10 2015 Latest operation return code: OK
Number of successes: 82 Number of failures: 0
Operation time to live: Forever
Specify the level of sensitivity to changes of tracked objects to 10 seconds of down delay and
1 second of up delay using the delay down 10 up 1 command. The delay helps to alleviate the
effect of flapping objects—objects that are going down and up rapidly. In this situation, if the
DNS server fails momentarily and comes back up within 10 seconds, there is no impact.
R1(config-track)# delay down 10 up 1
R1(config-track)# exit
R1(config)#
To view routing table changes as they happen, first enable the debug ip routing command.
R1# debug ip routing
IP routing debugging is on R1#
Configure the floating static route that will be implemented when tracking object 1 is active.
Use the ip route [Link] [Link] [Link] 2 track 1 command to create a floating static
default route via [Link] (ISP1). Notice that this command references the tracking
object number 1, which in turn references IP SLA operation number 11.
R1(config)# ip route [Link] [Link] [Link] 2 track 1
R1(config)#
Jan 10 [Link].119: RT: updating static [Link]/0 (0x0) : via [Link] 0 1048578
C [Link]/24 is directly connected, Loopback0 L [Link]/32 is directly
connected, Loopback0
[Link]/24 is variably subnetted, 2 subnets, 2 masks C [Link]/30 is
directly connected, Serial0/0/0
L [Link]/32 is directly connected, Serial0/0/0 [Link]/24 is
variably subnetted, 2 subnets, 2 masks
C [Link]/30 is directly connected, Serial0/0/1 L [Link]/32 is
directly connected, Serial0/0/1 R1#

Pillai HOC College of Art, Science and Commerce Page | 29


Modern Networking [Link] Sem-2

PRACTICAL NO: 07
AIM: Configuring Basic MPLS Using OSPF
Step 1 – IP addressing of MPLS Core and OSPF
First bring 3 routers into your topology R1, R2, R3 position them as below. We are going to
address the routers and configure ospf to ensure loopbackto loopback connectivity between
R1 and R3

Pillai HOC College of Art, Science and Commerce Page | 30


Modern Networking [Link] Sem-2

You should now have full ip connectivity between R1, R2, R3 to verify thiswe need to see if
we can ping between the loopbacks of R1 and R3

You could show the routing table here, but the fact that you can ping between the loopbacks
is verification enough and it is safe to move on.
Step 2 – Configure LDP on all the interfaces in the MPLS Core
In order to run MPLS you need to enable it, there are two ways to do this.
At each interface enter the mpls ip command
Under the ospf process use the mpls ldp autoconfig command
For this tutorial we will be using the second option, so go int the ospf process and enter mpls
ldp autoconfig – this will enable mpls label distribution protocol on every interface running
ospf under that specificprocess.

You should see log messages coming up showing the LDP neighbors are up

To verify the mpls interfaces the command is very simple – sh mpls interface
This is done on R2 and you can see that both interfaces are running mplsand using LDP

You can also verify the LDP neighbors with the sh mpls ldp neighbors command.
We now need to repeat this process for R3 & R6

Pillai HOC College of Art, Science and Commerce Page | 31


Modern Networking [Link] Sem-2

Router 6 will peer OSPF using process number 2 to a VRF configured onR3. It will use the
local site addressing of [Link]/24.

We also need to configure a VRF onto R3 as well.


So now we have configured the VRF on R3 we need to move the interface F0/1 into that VRF
R3
int f0/1
ip vrf forwarding RED
Now notice what happens when you do that – the IP address is removed
R3(config-if)#ip vrf forwarding RED

% Interface FastEthernet0/1 IP address 192.168.2.1removed due to


enabling VRF RED

You just need to re-apply it


R3
int f0/1
ip address [Link] [Link]

Now if we view the config on R3 int f0/1 you can see the VRF configured.

R1,R2,R3 form the MPLS Core and are running OSPF with all loopbacks running a /32
address and all have full connectivity. R1 and R3 are peeringwith MP-BGP. LDP is enabled
on all the internal interfaces. The external interfaces of the MPLS core have been placed into

Pillai HOC College of Art, Science and Commerce Page | 32


Modern Networking [Link] Sem-2

a VRF called RED and then a site router has been joined to that VRF on each side of the
MPLS core – (These represent a small office)
The final step to get full connectivity across the MPLS core is to redistributethe routes in
OSPF on R1 and R3 into MP-BGP and MP-BGP into OSPF, this is what we are going to do
now.
We need to redistribute the OSPF routes from R4 into BGP in the VRF on R1, the OSPF
routes from R6 into MP-BGP in the VRF
Before we start lets do some verifications
Check the routes on R4

R4#sh ip route

[Link]/32 is subnetted, 1 subnets

C [Link] is directly connected, Loopback0

on R3 and then theroutes in MP-BGP in R1 and R3 back out to OSPF

Type escape sequence to


[Link] the route to

[Link]

1 [Link] 20 msec 8 msec 8 msec

2 [Link] [MPLS: Labels 17/20 Exp 0] 36 msec 40 msec


36 msec

3 [Link] [MPLS: Label 20 Exp 0] 16 msec 40 msec 16msec

4 [Link] 44 msec 40 msec 56 msecR4#

Pillai HOC College of Art, Science and Commerce Page | 33


PILLAI HOC COLLEGE OF ART, SCIENCE & COMMERCE
UNIVERSITY OF MUMBAI
COMPUTER VISION
[Link]. (Information Technology) Part-I

Submitted by
Aditya Rupesh Koli
Seat No: 1312543

DEPARTMENT OF INFORMATION TECHNOLOGY


PILLAI HOC COLLEGE OF ART, SCIENCE & COMMERCE, RASAYANI
NAAC Accredited 'A+' Grade, Cycle II & ISO 9001:2015 Certified
(Affiliated to Mumbai University)
RASAYANI-410207, MAHARASHTRA
2024-2025
MAHATMA EDUCATION SOCIETY’S
PILLAI HOC COLLEGE OF ART, SCIENCE & COMMERCE, RASAYANI
NAAC Accredited 'A+' Grade, Cycle II & ISO 9001:2015 Certified
(Affiliated to Mumbai University)
RASAYANI-410207, MAHARASHTRA

INFORMATION TECHNOLOGY

CERTIFICATE
This is to certify that the experiment work entered in this journal is as per the syllabus
in [Link]. (Information Technology) Part-I, Semester-II; class prescribed by
University of Mumbai for Computer Vision, of Mahatma Education Society’s Pillai
HOC College of Arts, Science & Commerce, Rasayani by Aditya Rupesh Koli
during Academic year 2024-2025.
Seat No: 1312543

In-Charge Co-Ordinator

External Examiner Principal

Date College Seal


COMPUTER VISION
INDEX
Practical Title Date Page Signature
No. No.
01 Perform Geometric 01
Transformation
A. Image Scaling
B. Image Shrinking
C. Image Rotation
D. Affine Transformation
E. Perspective Transformation
F. Shearing X-axis
G. Shearing Y-axis
H. Reflected Image
I. Cropped Image
02 Perform Image Stitching 11
03 Perform Camera Calibration 13
04 Face & Object Detection 14
A. Face Detection
B. i. Object Detection ii. Line
Detection iii. Hough Transform
C. Pedestrian Detection
D. Face Recognition
05 Object Detection and Tracking 20
from Video A. Basic Detection
B. Count Faces
C. Object Tracking using
Homography
06 Perform Colorization 23
07 Perform Text Detection and 24
Recognition
08 Construct 3D Model from Images 25
09 Perform Feature Extraction using 26
RANSAC
Computer Vision [Link] Sem-2

PRACTICAL NO: 01
AIM: A] Perform Geometric transformation.
Theory:
Geometric Transformations:
Geometric transformation is a fundamental technique used in image processing that involves
manipulating the spatial arrangement of pixels in an image. It is used to modify the geometric
properties of an image, such as its size, shape, position, and orientation.
OpenCV provides two transformation functions, [Link] and [Link],
with which you can have all kinds of transformations. [Link] takes a 2x3
transformation matrix while [Link] takes a 3x3 transformation matrix as input.
Translation
Translation is the shifting of object‘s location. If you know the shift in (x,y) direction, let it be
you can create the transformation matrix M as follows:

You can take make it into a NumPy array of type np.float32 and pass it into [Link]()
function. See below example for a shift of (100,50):
Warning:
Third argument of the [Link]() function is the size of the output image, which
should
be in the form of (width, height). Remember width = number of columns, and height =
number of rows.
import cv2
import [Link] as plt
import numpy as np
img=[Link]("/content/cherry blossom [Link]")
img_rqb=[Link](img,cv2.COLOR_BGR2RGB) rows,cols,channels=img_rqb.shape
M=np.float32([[1,0,100],[0,1,50]])
dst=[Link](img_rqb,M,(cols,rows)) fig,axs=[Link](1,2,figsize=(7,4))
axs[0].imshow(img_rqb)
axs[0].set_title('Orignal image')
axs[1].imshow(dst)
axs[1].set_title('Translated image') plt.tight_layout()
[Link]()
Output:

Pillai HOC College of Art, Science and Commerce Page | 1


Computer Vision [Link] Sem-2

AIM: A] Image Scaling


Theory:
Scaling:
Scaling is just resizing of the image. OpenCV comes with a function [Link]() for this
purpose. The size of the image can be specified manually, or you can specify the scaling
factor.
Different interpolation methods are used. Preferable interpolation methods are
cv2.INTER_AREA for shrinking and cv2.INTER_CUBIC (slow) & cv2.INTER_LINEAR
for zooming. By default, interpolation method used is cv2.INTER_LINEAR for all resizing
purposes. You can resize an input image either of following methods:

import cv2
import [Link] as plt
import numpy as np
[Link]("/content/cherry blossom [Link]")
img_rgb=[Link](img,cv2.COLOR_BGR2RGB)
rows, cols, channels=img_rgb.shape
resize_img = [Link](img_rgb,(0,0), fx=2, fy=2, interpolation=cv2.INTER_CUBIC)
[Link](121), [Link](img_rgb), [Link]('Original Image')
[Link](122), [Link](resize_img), [Link]('Zoomed Image')
[Link]()

Output:

Pillai HOC College of Art, Science and Commerce Page | 2


Computer Vision [Link] Sem-2

AIM: B]Image Shrinking


Theory:
Shrinking:
Image shrinking in Python involves reducing the dimensions of an image, effectively making
it smaller while maintaining its aspect ratio. This process is commonly done using libraries
like PIL (Python Imaging Library) or its fork, Pillow. By resizing the image to smaller
dimensions, either by specifying new dimensions or a scaling factor, you can achieve the
desired reduction in size.
This is useful for tasks like image compression, thumbnail generation, or preparing images
for web display, where smaller file sizes are advantageous. The process typically involves
opening the image, calculating the new dimensions, resizing the image accordingly, and then
saving the resized image to a new file.
import cv2
import [Link] as plt
import numpy as np
img = [Link]("/content/cherry blossom [Link]")
img_rgb = [Link](img, cv2.COLOR_BGR2RGB)
rows, cols, channels = img_rgb.shape
resize_img = [Link](img_rgb,(0,0), fx=0.7, fy=0.7, interpolation=cv2.INTER_AREA)
[Link](121), [Link](img_rgb), [Link]('Original Image')
[Link](122), [Link](resize_img), [Link]('Shrinked Image')
[Link]()

Output:

Pillai HOC College of Art, Science and Commerce Page | 3


Computer Vision [Link] Sem-2

AIM: C] Image Rotation Theory: Rotation:


Rotation of an image for an angle is achieved by the transformation matrix of the form

But OpenCV provides scaled rotation with adjustable center of rotation so that you can rotate
at any location you prefer. Modified transformation matrix is given by

where:

To find this transformation matrix, OpenCV provides a function, cv2.getRotationMatrix2D.


Check below example which rotates the image by 90 degree with respect to center without
any scaling.
import cv2
import [Link] as plt
import numpy as np
img=[Link]("/content/cherry blossom [Link]")
img_rgb = [Link] (img,cv2.COLOR_BGR2RGB)
rows, cols, channels = img_rgb.shape
center = (cols // 2, rows // 2)
angle = -90
scale= 1
rotation_matrix = cv2.getRotationMatrix2D (center, angle, scale)
axs[0].set_title("Original image")
axs[1].imshow(rotated_image)
axs[1].set_title("Rotated image")
[Link]()
plt.tight_layout()
Output:

Pillai HOC College of Art, Science and Commerce Page | 4


Computer Vision [Link] Sem-2

AIM: D] Affine Transformation


Theory:
In affine transformation, all parallel lines in the original image will still be parallel in the
output image. To find the transformation matrix, we need three points from input image and
their corresponding locations in output image. Then [Link] will create a
2x3 matrix which is to be passed to [Link].

import cv2
import [Link] as plt
import numpy as np
img= [Link]("/content/cherry blossom [Link]")
img_rgb = [Link](img, cv2.COLOR_BGR2RGB)
rows, cols, channels = img_rgb.shape
ptsl= np.float32([[50,50], [200,50],[50,200]])
pts2 =np.float32([[10,100],[200,50],[100,250]])
M= [Link](ptsl,pts2)
dst = [Link](img_rgb,M,(cols,rows))
[Link](121), [Link](img_rgb), [Link]('Original Image')
[Link](122), [Link](dst), [Link]('Output Image')
[Link]()

Output:

Pillai HOC College of Art, Science and Commerce Page | 5


Computer Vision [Link] Sem-2

AIM: E] Perspective Transformation.


Theory:
For perspective transformation, you need a 3x3 transformation matrix. Straight lines will
remain straight even after the transformation. To find this transformation matrix, you need 4
points on the input image and corresponding points on the output image. Among these 4
points, 3 of them should not be collinear. Then transformation matrix can be found by the
function
[Link]. Then apply [Link] with this 3x3 transformation
matrix.

import cv2
import [Link] as plt
import numpy as np
img = [Link]("/content/cherry blossom [Link]")
img_rgb = [Link](img, cv2.COLOR_BGR2RGB)
rows, cols, channels = img_rgb.shape
ptsl= np.float32([[133,34], [226,16], [133,206], [226,219]])
pts2= np.float32([[0,0],[300,0], [0,300],[300,300]])
M = [Link](ptsl,pts2)
dst= [Link] (img, M, (300,300))
[Link](121), [Link](img_rgb), [Link]('Original Image')
[Link](122), [Link](dst), [Link]('Output Image')
[Link]()

Output:

Pillai HOC College of Art, Science and Commerce Page | 6


Computer Vision [Link] Sem-2

AIM: F] Shearing X-axis.


Theory:
Shearing deals with changing the shape and size of the 2D object along x-axis and y- axis. It
is similar to sliding the layers in one direction to change the shape of the 2D object. It is an
ideal technique to change the shape of an existing object in a two dimensional plane. In a
two- dimensional plane, the object size can be changed along X direction as well as Y
direction.
Shear:
In x shear, the y co-ordinates remain the same but the x co-ordinates changes.
import cv2
import [Link] as plt
import numpy as np
[Link]("/content/cherry blossom [Link]")
img_rgb=[Link](img,cv2.COLOR_BGR2RGB)
rows, cols, channels=img_rgb.shape M=np.float32([[1, 0.5, 0], [0, 1, 0], [0, 0, 1]])
dst= [Link](img_rgb, M, (int(cols*1.5), int(rows*1.5)))
[Link](121), [Link](img_rgb), [Link]('Original Image')
[Link](122), [Link](dst),
[Link]('Output Image')
[Link]()

Output:

Pillai HOC College of Art, Science and Commerce Page | 7


Computer Vision [Link] Sem-2

AIM: G] Shearing Y-axis.


Theory:
Shearing deals with changing the shape and size of the 2D object along x-axis and y- axis. It
is similar to sliding the layers in one direction to change the shape of the 2D [Link] is an
ideal technique to change the shape of an existing object in a two dimensional plane. In a
two- dimensional plane, the object size can be changed along X direction as well as Y
direction.
Y-Shear:
In y shear, the x co-ordinates remain the same but the y co-ordinates changes.

import cv2
import [Link] as plt
import numpy as np
[Link]("/content/cherry blossom [Link]")
img_rgb=[Link](img,cv2.COLOR_BGR2RGB)
rows, cols, channels=img_rgb.shape
M= np.float32([[1,0,0],[0.5, 1,0],[0, 0,1]])
dst = [Link](img_rgb, M, (int(cols*1.5), int(rows*1.5)))
[Link](121),
[Link](img_rgb), [Link]('Original Image')
[Link](122), [Link](dst), [Link]('Output Image')
[Link]()

Output:

Pillai HOC College of Art, Science and Commerce Page | 8


Computer Vision [Link] Sem-2

AIM: H] Reflected Image.


Theory
Image Reflection
Image reflection is used to flip the image vertically or horizontally. For reflection along the x-
axis, we set the value of Sy to -1, Sx to 1, and vice-versa for the y-axis reflection.
import cv2
import [Link] as plt
import numpy as np

[Link]("/content/cherry blossom [Link]")


img_rgb=[Link](img,cv2.COLOR_BGR2RGB)
rows,cols, channels=img_rgb.shape
M = np.float32([[1,0,0],[0,-1,rows], [0,0,1]])
dst = [Link] (img_rgb, M,((cols),(rows)))
[Link](121),
[Link](img_rgb), [Link]('Original Image')
[Link](122), [Link](dst), [Link]('Output Image')
[Link]()

Output:

Pillai HOC College of Art, Science and Commerce Page | 9


Computer Vision [Link] Sem-2

AIM: I] Cropped Image.


Theory:
Image Cropping
Cropping is the removal of unwanted outer areas from an image.

import cv2
import [Link] as plt
import numpy as np
[Link]("/content/cherry blossom [Link]")
img_rgb=[Link](img,cv2.COLOR_BGR2RGB)
rows, cols, channels=img_rgb.shape
dst =img[100:300, 100:300]
[Link](121), [Link](img_rgb), [Link]('Original Image')
[Link](122), [Link](dst), [Link]('Output Image')
[Link]()

Output:

Pillai HOC College of Art, Science and Commerce Page | 10


Computer Vision [Link] Sem-2

PRACTICAL NO: 02
AIM: Perform Image Stitching.
Theory:
Image stitching is the process of combining multiple overlapping images to create a seamless,
high-resolution output image. This technique is commonly used to create panoramic images,
virtual tours, and even some medical imaging applications.
Image stitching involves several steps:
Feature detection: Identifying and extracting unique features (e.g., corners, edges) from each
input image. Compute the SIFT-key points and descriptors for both the images.
Feature matching: Finding correspondences between features in the overlapping regions of
the input images. Compute distances between every descriptor in one image and every
descriptor in the other image. Select the top ‗m‘ matches for each descriptor of an image.
Homography estimation: Estimating the transformation (e.g., rotation, scaling, translation)
that aligns the input images. Run RANSAC to estimate homography
Warping: Applying the estimated transformation to the input images. Warp to align for
stitching
Blending: Combining the warped images into a single seamless output image. Now stitch
them together
Explanation of Code:
Firstly, we have to find out the features matching in both the images. These best matched
features act as the basis for stitching. We extract the key points and sift descriptors for both
the images as follows:
sift = cv2.SIFT_create()
# find the keypoints and descriptors with SIFT kp1, des1 =
[Link](img1,None) kp2, des2 = [Link](img2,None)
kp1 and kp2 are keypoints, des1 and des2 are the descriptors of the respective [Link],
the obtained descriptors in one image are to be recognized in the image too. We do that as
follows:
import cv2
import numpy as nm
import [Link] as plt
from random import randrange
img = [Link]("/content/cherry blossom
[Link]") imgl =
[Link](img,cv2.COLOR_BGR2GRAY)
img = [Link]("/content/cherry blossom
[Link]") img2 =
[Link](img,cv2.COLOR_BGR2GRAY)
sift = cv2.SIFT_create()
kpl, desl = [Link](imgl,
None) kp2, des2 =[Link]
(img2, None) bf = [Link]()
matches= [Link]
(desl,des2, k=2) good = []
for m in matches:
if m[0].distance < 0.5*m[1].distance:
[Link](m)
matches =
[Link](good) if
len (matches[:,0]) >4:

Pillai HOC College of Art, Science and Commerce Page | 11


Computer Vision [Link] Sem-2

src = nm.float32([kpl[[Link]].pt for m in


matches[:,0]]).reshape(-1,1,2) dst = nm.float32([kp2[[Link]].pt
for m in matches[:,0]]).reshape(-1,1,2) H, masked =
[Link](src, dst, [Link], 5.0)
prin
t(H)
else:
raise AssertionError("Can't find enough keypoints.")
dst = [Link](img, H, ([Link][1] + [Link][1],
[Link][0])) [Link] (122), [Link](dst),[Link]("Warped Image")
[Link]()
[Link]("resultant_stitched_panorama.jpg",dst)
[Link](dst)
[Link]()

Input images:

Output:

Pillai HOC College of Art, Science and Commerce Page | 12


Computer Vision [Link] Sem-2

PRACTICAL NO: 03
AIM: Perform Camera Calibration.
Theory:
A camera is an integral part of several domains like robotics, space exploration, etc camera is
playing a major role. It helps to capture each and every moment and helpful for many
analyses. In order to use the camera as a visual sensor, we should know the parameters of the
camera. Camera Calibration is nothing but estimating the parameters of a camera,
parametersabout the camera are required to determine an accurate relationship between a3D
point in the real world and its corresponding 2D projection (pixel) in the image captured by
that calibrated camera.
import numpy as np
import cv2 as cv import glob
import [Link] as plt
criteria = (cv.TERM_CRITERIA_EPS + cv.TERM_CRITERIA_MAX_ITER, 30, 0.001)
objp = [Link]((6*7, 3), np.float32)
objp[:, :2] = [Link][0:7, 0:6].[Link](-1, 2)
objpoints = [] imgpoints = []
file images = [Link]('/content/[Link]') for fname in images:
img = [Link](fname) if img is None:
corners2 = [Link](gray, corners, (11, 11), (-1, -1), criteria)
[Link](corners2)
[Link](img, (7, 6), corners2, ret)
# Display the image with chessboard corners using matplotlib [Link]([Link](img,
cv.COLOR_BGR2RGB)) [Link](fname) [Link]()else:
print(f"Chessboard corners not found in image {fname}")
empty if len(objpoints) > 0 and len(imgpoints)0:
ret, mtx, dist, rvecs, tvecs = [Link](objpoints, imgpoints, [Link][::-1], None,
None)
print("Camera matrix: ")
print(mtx) print("Distortion
Output:

Pillai HOC College of Art, Science and Commerce Page | 13


Computer Vision [Link] Sem-2

PRACTICAL NO: 04
AIM: A] Perform the following Face detection.
Theory:
Face detection involves identifying a person‘s face in an image or video. Thisis done by
analyzing the visual input to determine whether a person‘s facial features are present. Since
human faces are so diverse, face detection models typically need to be trained on large
amounts of input data for them to be accurate. The training dataset must contain a sufficient
representation of people who come from different backgrounds, genders, and [Link]
algorithms also need to be fed many training samples comprising different lighting, angles,
and orientations to make correct predictions in real- world [Link] nuances make
face detection a non-trivial, time- consuming task thatrequires hours of model training and
millions of data samples.
face detection

import cv2
import [Link] as plt
# Specify the path to the image and cascade classifier
imagePath = '/content/[Link]'
classifierPath = '/content/haarcascade_frontalface_default.xml' img = [Link](imagePath)
correctly if img is None:
raise ValueError(f"Failed to load image from path:
{imagePath}") else:
print(f'Image shape: {[Link]}')
gray_image = [Link](img, cv2.COLOR_BGR2GRAY)
face_classifier = [Link](classifierPath)
faces = face_classifier.detectMultiScale(gray_image, scaleFactor=1.1, minNeighbors=5,
minSize=(40, 40))
for (x, y, w, h) in faces:
[Link](img, (x, y), (x + w, y + h), (0, 255, 0), 4)
matplotlib img_rgb = [Link](img, cv2.COLOR_BGR2RGB) [Link](figsize=(20,
10)) [Link](img_rgb)
[Link]('off') [Link]()

Output:

Pillai HOC College of Art, Science and Commerce Page | 14


Computer Vision [Link] Sem-2

AIM: B] Perform the following Object detection.


Theory
Object Detection
• Haar cascade:Basically, the Haar cascade technique is an approach based on machine
learning where we use a lot of positive and negative images to train the classifier to
classify between the images. Haar cascade classifiers are considered as the effective
way to do object detection with the OpenCV library.
• Positive images: These are the images that contain the objects which we want to be
identified from the classifier.
• Negative Images: These are the images that do not contain any object that we want to
be detected by the classifier, and these can be images of everything else
import cv2
from matplotlib import pyplot as plt
# Load the image
image_path = "/content/[Link]" image = [Link](image_path)
if image is None:
print(f"Failed to load image {image_path}") else:
image_gray = [Link](image, cv2.COLOR_BGR2GRAY) image_rgb =
[Link](image, cv2.COLOR_BGR2RGB)
# Load the cascade classifier cascade_path =
'/content/haarcascade_frontalcatface.xml' cascade = [Link](cascade_path)
if [Link]():
# Detect objects in the image
detections = [Link](image_gray, minSize=(30, 30)) detection_count =
len(detections)
# Draw rectangles around detected objects if detection_count != 0:
for (x, y, width, height) in detections:
[Link](image_rgb, (x, y), (x + width, y + height), (0, 255, 0), 9)
# Display the image with detections [Link](image_rgb) [Link](f"Detections:
{detection_count}") [Link]('off') #
Hide axis [Link]()
Output:

Pillai HOC College of Art, Science and Commerce Page | 15


Computer Vision [Link] Sem-2

AIM: C] Perform the following Line detection.


import cv2
import numpy as np
from [Link] import cv2_imshow image = [Link]('/content/[Link]')
cv2_imshow(image)
line_list = []
gray = [Link](image, cv2.COLOR_BGR2GRAY)
edges = [Link](gray, 50, 150, apertureSize=3)
lines = [Link]( edges,
rho=2, theta=[Link] / 180, threshold=100,
minLineLength=20, maxLineGap=5
)
if lines is not None: for points in lines:
x1, y1, x2, y2 = points[0]
[Link](image, (x1, y1), (x2, y2), (0, 255, 0), 2)
line_list.append([(x1, y1), (x2, y2)]) cv2_imshow(image)
Input image

Output:

Pillai HOC College of Art, Science and Commerce Page | 16


Computer Vision [Link] Sem-2

AIM: D] Perform the following Hough transform.


import cv2
import numpy as np
from [Link] import cv2_imshow
# Read the image
img = [Link]('/content/[Link]')
# Display the original image cv2_imshow(img)
# Convert to grayscale
gray = [Link](img, cv2.COLOR_BGR2GRAY)
# Apply a blur to the grayscale image gray_blurred = [Link](gray, (3, 3))
# Detect circles using HoughCircles detected_circles = [Link](
gray_blurred, cv2.HOUGH_GRADIENT, 1,
20,
param1=100, param2=50, minRadius=2, maxRadius=80
)
# Draw detected circles on the image if detected_circles is not None:
detected_circles = np.uint16([Link](detected_circles)) for pt in detected_circles[0, :]:
a, b, r = pt[0], pt[1], pt[2]
[Link](img, (a, b), r, (0, 255, 0), 2)
[Link](img, (a, b), 1, (0, 0, 255), 3)
# Display the image with detected circles cv2_imshow(img)

Output:

Pillai HOC College of Art, Science and Commerce Page | 17


Computer Vision [Link] Sem-2

AIM: E] Perform the following Pedestrian detection.


import cv2 import imutils
from [Link]
import cv2_imshow hog = [Link]()
[Link](cv2.HOGDescriptor_getDefaultPeopleDetector())
image = [Link]('/content/people_walking.jpg')
image = [Link](image, width=min(400, [Link][1]))
(regions, _) = [Link](image, winStride=(4, 4), padding=(4, 4), scale=1.05) for
(x, y, w, h) in regions:
[Link](image, (x, y), (x + w, y + h), (0, 0, 255), 2) cv2_imshow(image)

Output:

Pillai HOC College of Art, Science and Commerce Page | 18


Computer Vision [Link] Sem-2

AIM: F] Perform the following Face Recognition.


import cv2
from [Link]
import cv2_imshow img = [Link]('/content/[Link]')
gray = [Link](img, cv2.COLOR_BGR2GRAY)
face_cascade = [Link]([Link] +
'haarcascade_frontalface_default.xml')
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5) for (x, y, w,
h) in faces:
[Link](img, (x, y), (x+w, y+h), (255, 0, 255), 2) font =
cv2.FONT_HERSHEY_SIMPLEX
text = 'I am Manasi Singh' font_scale = 1
font_thickness = 1
text_size, _ = [Link](text, font, font_scale, font_thickness) text_x = 20
text_y = 30 + text_size[1]
[Link](img, text, (text_x, text_y), font, font_scale, (0, 0, 0), font_thickness,
cv2.LINE_AA)
scale_percent = 20
width = int([Link][1] * scale_percent / 100) height = int([Link][0] * scale_percent /
100) dim = (width, height)
resized_img = [Link](img, dim, interpolation=cv2.INTER_AREA)
cv2_imshow(resized_img)

Output:

Pillai HOC College of Art, Science and Commerce Page | 19


Computer Vision [Link] Sem-2

PRACTICAL NO: 05
AIM: A] Implement object detection and tracking from video
import cv2
from [Link] import cv2_imshow from tracker import *
tracker = EuclideanDistTracker()
cap = [Link]("/content/highway_video.mp4")
object_detector = cv2.createBackgroundSubtractorMOG2(history=100, varThreshold=40)
while True:
ret, frame = [Link]()
if not ret:
print("End of video or cannot read the frame.")
break # Exit the loop if the video ends or if there's an issue height, width, channels =
[Link] # Unpack all three values print(height, width)
roi = frame[340:720, 500:800] mask = object_detector.apply(roi)
_, mask = [Link](mask, 254, 255, cv2.THRESH_BINARY)
contours, _ = [Link](mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
detections = []
for cnt in contours:
area = [Link](cnt) if area > 100:
x, y, w, h = [Link](cnt)
[Link](roi, (x, y), (x + w, y + h), (0, 255, 0), 2) [Link]([x, y, w, h])
boxes_ids = [Link](detections) for box_id in boxes_ids:
x, y, w, h, id = box_id
[Link](roi, str(id), (x, y - 15), cv2.FONT_HERSHEY_PLAIN, 1, (255, 0, 0), 2)
[Link](roi, (x, y), (x + w, y + h), (0, 255, 0), 3) # Display images using cv2_imshow
cv2_imshow(roi) cv2_imshow(frame) cv2_imshow(mask) key = [Link](30) if key ==
27:
break
[Link]() [Link]()

Output:

PRACTICAL NO: 05

Pillai HOC College of Art, Science and Commerce Page | 20


Computer Vision [Link] Sem-2

AIM: B] Implement object detection and tracking from video. (Count number of Faces
using Python)
import cv2
import numpy as np import dlib
from [Link] import cv2_imshow cap =
[Link]("/content/people.mp4") detector = dlib.get_frontal_face_detector() while
True:
ret, frame = [Link]() if not ret:
break
frame = [Link](frame, 1)
gray = [Link](frame, cv2.COLOR_BGR2GRAY)
faces = detector(gray)
for i, face in enumerate(faces): x, y = [Link](), [Link]()
x1, y1 = [Link](), [Link]() [Link](frame, (x, y), (x1, y1), (0, 255, 0), 2)
[Link](frame, 'face num' + str(i + 1), (x - 10, y - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 3)
print(face, i + 1
frame = [Link](frame, (1000, 600)) cv2_imshow(frame)
if [Link](1) & 0xFF == ord('q'): break
[Link]() [Link]()

Output:

Pillai HOC College of Art, Science and Commerce Page | 21


Computer Vision [Link] Sem-2

AIM: C] Implement object detection and tracking from video. (Object Tracking using
Homography)
import cv2
import numpy as np
from [Link] import cv2_imshow
img = [Link]("/content/fd_img.jpg", cv2.IMREAD_GRAYSCALE) cap =
[Link]("/content/fd.mp4")
sift = cv2.SIFT_create()
kp_image, desc_image = [Link](img, None) index_params =
dict(algorithm=0, trees=5)
search_params = dict()
flann = [Link](index_params, search_params) ret, frame = [Link]()
if not ret:
print("Failed to read video") else:
grayframe = [Link](frame, cv2.COLOR_BGR2GRAY) kp_grayframe, desc_grayframe
= [Link](grayframe, None) matches = [Link](desc_image,
desc_grayframe, k=2)
good_points = [] for m, n in matches:
if [Link] < 0.8 * [Link]: # Slightly higher ratio good_points.append(m)
all_matches = [Link](img, kp_image, frame, kp_grayframe, [m[0] for m in
matches], None, flags=cv2.DrawMatchesFlags_NOT_DRAW_SINGLE_POINTS)
cv2_imshow(all_matches) if len(good_points) > 10:
# Extract location of good matches
query_pts = np.float32([kp_image[[Link]].pt for m in good_points]).reshape(-1,
h, w = [Link]
pts = np.float32([[0, 0], [0, h], [w, h], [w, 0]]).reshape(-1, 1, 2) dst =
[Link](pts, matrix)
matching_output = [Link](img, kp_image, frame, kp_grayframe, good_points,
None, flags=cv2.DrawMatchesFlags_NOT_DRAW_SINGLE_POINTS)
cv2_imshow(matching_output) [Link]() [Link]()

Output:

Pillai HOC College of Art, Science and Commerce Page | 22


Computer Vision [Link] Sem-2

PRACTICAL NO: 06
AIM: Perform Colorization.

Output:

Pillai HOC College of Art, Science and Commerce Page | 23


Computer Vision [Link] Sem-2

PRACTICAL NO: 07
AIM: Perform Text Detection and Recognition

Output

Pillai HOC College of Art, Science and Commerce Page | 24


Computer Vision [Link] Sem-2

PRACTICAL NO: 08
AIM: Construct 3D model from Images.
from PIL import Image import numpy as np
import [Link] as plt

def shift_image(img, depth_img, shift_amount=10): img = [Link]("RGBA")


data = [Link](img)
depth_img = depth_img.convert("L") depth_data = [Link](depth_img)
deltas = ((depth_data / 255.0) * float(shift_amount)).astype(int)
shifted_data = np.zeros_like(data) height, width, _ = [Link]
for y, row in enumerate(deltas):
for x, dx in enumerate(row):
if 0 <= x + dx < width: shifted_data[y, x + dx] = data[y, x]
shifted_image = [Link](shifted_data.astype(np.uint8))
# Load images
img_path = "/content/sample_data/[Link]" # Replace with your image path
depth_img_path = "/content/sample_data/[Link]" # Replace with your depth image path
# Original Image axs[0].imshow(img) axs[0].set_title('Original Image') axs[0].axis('off')

# Shifted Image axs[1].imshow(shifted_img) axs[1].set_title('Shifted Image')


axs[1].axis('off')
[Link]()

Output

Pillai HOC College of Art, Science and Commerce Page | 25


Computer Vision [Link] Sem-2

PRACTICAL NO: 09
AIM: Perform Feature extraction using RANSAC.
import cv2
import numpy as np
import [Link] as plt
img1_color = [Link]("/content/sample_data/[Link]") img2_color =
[Link]("/content/sample_data/[Link]") img1 = [Link](img1_color,
cv2.COLOR_BGR2GRAY) img2 = [Link](img2_color, cv2.COLOR_BGR2GRAY)
height, width = [Link]
orb_detector = cv2.ORB_create(5000)
kp1, d1 = orb_detector.detectAndCompute(img1, None) kp2, d2 =
orb_detector.detectAndCompute(img2, None)
matcher = [Link](cv2.NORM_HAMMING, crossCheck=True) matches =
[Link](d1, d2)
matches = sorted(matches, key=lambda x: [Link]) matches = matches[:int(len(matches) *
0.9)] no_of_matches = len(matches)
p1 = [Link]((no_of_matches, 2)) p2 = [Link]((no_of_matches, 2))
axs[0].set_title('Original Image')
axs[0].axis('off')
axs[1].imshow([Link](transformed_img, cv2.COLOR_BGR2RGB))
axs[1].set_title('Transformed Image')

Output:

Pillai HOC College of Art, Science and Commerce Page | 26

You might also like