Lab - Linux and Shell Programming: Assignment 2
Professor:- Dr Sanjay Tyagi
Assignment:- Lab-Linux and Shell Programming
Name:- Milan Vashisth
Student Id:- 10776048
Sem:- MCA 2nd
Enrollment No:- 241MCA1/0838
Q-1 Explain the structure of the Linux file system, including the roles of the
boot block, super block, inode block, and data block. Create a directory
structure and demonstrate the use of basic and advanced file commands
(such as mkdir, rmdir, ls, cp, mv, rm) to manipulate the file system. Include
examples and screenshots of your commands.?
Answer:- Linux File System Structure
The Linux file system is organized in a hierarchical structure, often referred
to as a directory tree. The top of the hierarchy is called the root directory,
denoted by a slash (/). Below the root directory, there are several important
directories such as /bin, /etc, /home, /var, and so on.
Key Components of the Linux File System:
1) Boot Block:- The boot block is the first block of the storage device. It
contains the boot loader, which is responsible for loading the operating
system into memory during the boot process.
2) Super Block:- The super block contains metadata about the file system,
such as its size, block size, number of free blocks, and information about
the inode table. It is crucial for the file system's integrity and operation.
3) Inode Block:- Inodes are data structures that store information about files
and directories, including their size, permissions, timestamps, and pointers
to data blocks. Each file or directory has a unique inode.
4) Data Block:- Data blocks store the actual content of files.
The inode contains pointers to these data blocks. Directory Structure and
File Commands Let's create a sample directory structure and demonstrate
the use of basic and advanced file commands.
Directory Structure and File Commands:-
1. Creating Directories (mkdir):-
mkdir -p /home/krishcity113/myproject/{src,bin,docs}
This command creates a directory structure:
Code
/home
└── krishcity113
└── myproject
├── src
├── bin
└── docs
2. Listing Files and Directories (ls):-
ls -l /home/krishcity113/myproject
This command lists the contents of the myproject directory in long format,
showing details like permissions, owner, size, and modification date.
2. Copying Files (cp):-
cp /home/krishcity113/original.txt /home/krishcity113/myproject/docs/
This command copies original.txt to the docs directory.
4. Moving and Renaming Files (mv):-
mv /home/krishcity113/myproject/docs/original.txt
/home/krishcity113/myproject/docs/renamed.txt
This command renames original.txt to renamed.txt.
5. Removing Files (rm):-
rm /home/krishcity113/myproject/docs/renamed.txt
This command removes renamed.txt.
6. Removing Directories (rmdir):-
rmdir /home/krishcity113/myproject/bin
This command removes the bin directory (only works if the directory is
empty).
Example Commands and Outputs
Create Directories:-
$ mkdir -p /home/krishcity113/myproject/{src,bin,docs}
List Directory Contents:-
$ ls -l /home/krishcity113/myproject
total 12
drwxr-xr-x 2 krishcity113 users 4096 Jan 14 15:50 bin
drwxr-xr-x 2 krishcity113 users 4096 Jan 14 15:50 docs
drwxr-xr-x 2 krishcity113 users 4096 Jan 14 15:50 src
Copy File:-
$ cp /home/krishcity113/original.txt /home/krishcity113/myproject/docs/
Move and Rename File:-
$ mv /home/krishcity113/myproject/docs/original.txt
/home/krishcity113/myproject/docs/renamed.txt
Remove File:-
$ rm /home/krishcity113/myproject/docs/renamed.txt
Remove Directory:-
$ rmdir /home/krishcity113/myproject/bin
Screenshot (Conceptual)
Since I cannot provide actual screenshots, below is a conceptual representation
of the command outputs:
Listing Directory Contents (ls -l /home/krishcity113/myproject)
Code
total 12
drwxr-xr-x 2 krishcity113 users 4096 Jan 14 15:50 bin
drwxr-xr-x 2 krishcity113 users 4096 Jan 14 15:50 docs
drwxr-xr-x 2 krishcity113 users 4096 Jan 14 15:50 src
Summary
1) Boot Block: Contains the boot loader.
2) Super Block: Contains file system metadata.
3) Inode Block: Stores information about files and directories.
4) Data Block: Stores the actual file content.
Q-2 Create a scheduled task using cron and crontab. Set up a job that runs
a specific script at regular intervals. Explain the process scheduling
mechanism in Linux and how cron, at, and batch are used to manage
scheduled tasks. Provide examples and screenshots
Answer:- Process Scheduling Mechanism in Linux
Linux uses a process scheduler to manage the execution of processes. The
scheduler decides which process runs at any given time, based on process
priority and other factors.
There are three main types of scheduling mechanisms in Linux:-
1) Real-Time Scheduling:- Used for processes that require immediate and
deterministic execution.
2) Batch Scheduling:- Used for background jobs that do not require
immediate execution.
3) Time-Sharing Scheduling:- Used for regular processes, where CPU time
is shared among them.
Tools for Managing Scheduled Tasks
cron:- cron is a time-based job scheduler that runs tasks at specified
intervals.
It uses crontab (cron table) files to store job schedules.
at:- at is used to schedule a one-time task to run at a specific time. It is
suitable for tasks that need to be executed once in the future.
batch:- batch is used to schedule tasks to run when the system load is low.
It is useful for non-urgent tasks that can wait until the system is less busy.
Creating a Scheduled Task Using cron and crontab
Let's create a scheduled task that runs a specific script at regular intervals
using cron and crontab.
1. Create a Script
Create a simple script to run.
For example:-
let's create a script that logs the current date and time to a file.
# /home/krishcity113/log_date.sh
#!/bin/bash
echo "Current Date and Time: $(date)" >> /home/krishcity113/date_log.txt
1. Make the script executable:
chmod +x /home/krishcity113/log_date.sh
2. Edit the Crontab
Open the crontab editor for the current user:- crontab -e
Add a new cron job to run the script every minute:
* * * * * /home/krishcity113/log_date.sh
Save and close the editor. This cron job will run the log_date.sh script every
minute.
3. Verify the Crontab Entry:-
List the current cron jobs to verify the entry:
crontab -l
You should see the cron job listed:
Code
* * * * * /home/krishcity113/log_date.sh
Examples of at and batch
Scheduling a One-Time Task with at
Schedule a task to run at a specific time (e.g., 2:30 PM):
echo "/home/krishcity113/log_date.sh" | at 14:30
Scheduling a Task with batch:-
Schedule a task to run when the system load is low:-
echo "/home/krishcity113/log_date.sh" | batch
Crontab Editor:-
Code
# Edit the crontab file
$ crontab -e
# Add the following line to the crontab file
* * * * * /home/krishcity113/log_date.sh
Verifying Crontab Entry
Code
$ crontab -l
* * * * * /home/krishcity113/log_date.sh
Q-3 Explore networking tools in Linux by using command such as ping,
nslookup, telnet, arp, netstat, route, Ōp, & rlogin. Provide examples of each
command in use and explain their significance in network troubleshooting
and management.
Answer:-
1. ping:- The ping command is used to check the connectivity between your
computer and another host by sending ICMP echo requests.
Example:- ping google.com
Explanation:- This command sends ICMP echo requests to google.com and
displays the response time. It helps determine if a host is reachable and
measures the round-trip time for messages sent.
2. nslookup:- The nslookup command is used to query DNS servers to
obtain domain name or IP address mapping.
Example:-nslookup google.com
Explanation:-This command queries the DNS server to get the IP address
associated with google.com. It's useful for diagnosing DNS issues.
3. telnet:- The telnet command is used to connect to a remote host using
the Telnet protocol. It's often used to test connectivity to TCP ports.
Example:- telnet google.com 80
Explanation:-This command attempts to connect to google.com on port 80
(HTTP). It's useful for checking if a specific port is open and accessible.
4. arp:- The arp command is used to display and manipulate the ARP
(Address Resolution Protocol) cache.
Example:- arp -a
Explanation:- This command displays the current ARP table, showing IP
addresses and their corresponding MAC addresses. It's useful for
diagnosing network issues related to IP-to-MAC address mapping.
5. netstat:- The netstat command provides network statistics and
information about network connections, routing tables, interface statistics,
masquerade connections, and multicast memberships.
Example:- netstat -tuln
Explanation:- This command displays all listening TCP and UDP ports with
numerical addresses. It's useful for checking which ports are open and
listening on a system.
6. route:- The route command is used to show and manipulate the IP
routing table.
Example:- route -n
Explanation:- This command displays the kernel's IP routing table with
numerical addresses. It's useful for viewing and managing the routing table.
7. ip:-The ip command is used to show and manipulate routing, devices,
policy routing, and tunnels.
Example:- ip a
Explanation:- This command displays all network interfaces and their IP
addresses. It's useful for managing network interfaces and configuring IP
addresses.
8. rlogin:-The rlogin command is used to log in to a remote host using the
rlogin protocol.
Example:- rlogin -l username remotehost
Explanation:- This command logs in to remotehost as username. It's useful
for accessing remote systems, though it's less common now due to security
concerns and the preference for SSH.
Q-4 Develop a shell script that uses condional statements and looping
constructs to automate a system maintenance task. The script should check
disk usage, clear temporary files, and generate a report. Provide the script
and explain each part of the code.
Answer:-
Shell Script (maintenance.sh)
#!/bin/bash
# Define the log file for the report
LOGFILE="/var/log/system_maintenance.log"
# Function to check disk usage
check_disk_usage()
echo "Checking disk usage..." | tee -a $LOGFILE
df -h | tee -a $LOGFILE
# Function to clear temporary files
clear_temp_files() {
echo "Clearing temporary files..." | tee -a $LOGFILE
TEMP_DIR="/tmp"
rm -rf ${TEMP_DIR}/* | tee -a $LOGFILE
echo "Temporary files cleared." | tee -a $LOGFILE
# Function to generate a report
generate_report()
echo "Generating report..." | tee -a $LOGFILE
echo "System Maintenance Report - $(date)" | tee -a $LOGFILE
echo "-----------------------------------------" | tee -a $LOGFILE
check_disk_usage
clear_temp_files
echo "-----------------------------------------" | tee -a $LOGFILE
echo "Report generated successfully." | tee -a $LOGFILE
# Main script execution
echo "Starting system maintenance..." | tee -a $LOGFILE
# Check if the log file exists, if not create it
if [ ! -f $LOGFILE ]; then
touch $LOGFILE
fi
# Generate the report
generate_report
echo "System maintenance completed." | tee -a $LOGFILE
Explanation:-
Shebang Line:- #!/bin/bash
This line indicates that the script should be run using the Bash shell.
Log File Definition:- LOGFILE="/var/log/system_maintenance.log"
This variable defines the path to the log file where the report will be stored.
Function to Check Disk Usage:-
check_disk_usage()
echo "Checking disk usage..." | tee -a $LOGFILE
df -h | tee -a $LOGFILE
This function uses the df -h command to check disk usage and appends the
output to the log file.
Function to Clear Temporary Files:-
clear_temp_files()
{
echo "Clearing temporary files..." | tee -a $LOGFILE
TEMP_DIR="/tmp"
rm -rf ${TEMP_DIR}/* | tee -a $LOGFILE
echo "Temporary files cleared." | tee -a $LOGFILE
This function clears all files in the /tmp directory and logs the action.
Function to Generate a Report:-
generate_report()
echo "Generating report..." | tee -a $LOGFILE
echo "System Maintenance Report - $(date)" | tee -a $LOGFILE
echo "-----------------------------------------" | tee -a $LOGFILE
check_disk_usage
clear_temp_files
echo "-----------------------------------------" | tee -a $LOGFILE
echo "Report generated successfully." | tee -a $LOGFILE
This function generates a maintenance report by calling the
check_disk_usage and clear_temp_files functions and appending the output
to the log file.
Main Script Execution:-:
echo "Starting system maintenance..." | tee -a $LOGFILE
# Check if the log file exists, if not create it
if [ ! -f $LOGFILE ]; then
touch $LOGFILE
fi
# Generate the report:-
generate_report
echo "System maintenance completed." | tee -a $LOGFILE
This section starts the system maintenance, checks if the log file exists
(creates it if not), and generates the report by calling the generate_report
function.
Usage:-
Save the script to a file named maintenance.sh.
Make the script executable:-
chmod +x maintenance.sh
Run the script with superuser privileges to ensure it can access and modify
necessary files:
sudo ./maintenance.sh
This script will check disk usage, clear temporary files, and generate a
report, saving the output to /var/log/system_maintenance.log.
Q-5 Write a shell script that accepts command-line arguments and performs
operaons based on the arguments provided. The script should include
opons for file manipulaon (e.g., copy, move, delete) and display appropriate
messages for each operaon. Provide the script and examples of its
execuon.
Answer:-
Shell Script (file_ops.sh)
#!/bin/bash
# Function to display usage information
usage()
echo "Usage: $0 {copy|move|delete} source [destination]"
exit 1
# Check if at least two arguments are provided
if [ $# -lt 2 ]; then
usage
fi
# Get the operation and source file from the command-line arguments
operation=$1
source=$2
destination=$3
# Perform the requested operation
case $operation in
copy)
if [ -z "$destination" ]; then
echo "Error: Destination path is required for copy operation."
usage
fi
cp "$source" "$destination"
if [ $? -eq 0 ]; then
echo "File copied from $source to $destination successfully."
else
echo "Failed to copy file from $source to $destination."
fi
;;
move)
if [ -z "$destination" ]; then
echo "Error: Destination path is required for move operation."
usage
fi
mv "$source" "$destination"
if [ $? -eq 0 ]; then
echo "File moved from $source to $destination successfully."
else
echo "Failed to move file from $source to $destination."
fi
;;
delete)
rm -f "$source"
if [ $? -eq 0 ]; then
echo "File $source deleted successfully."
else
echo "Failed to delete file $source."
fi
;;
*)
echo "Error: Invalid operation specified."
usage
;;
Esac
Explanation:-
Shebang Line:- #!/bin/bash
This line indicates that the script should be run using the Bash shell.
Usage Function:-
usage()
echo "Usage: $0 {copy|move|delete} source [destination]"
exit 1
This function displays the correct usage of the script and exits with a status
code of 1.
Argument Check:-
if [ $# -lt 2 ]; then
usage
Fi
This checks if at least two arguments are provided. If not, it calls the usage
function.
Retrieve Arguments:-
operation=$1
source=$2
destination=$3
This retrieves the operation (e.g., copy, move, delete), source file, and
destination from the command-line arguments.
Perform Operation:-
The script uses a case statement to perform the requested operation based
on the first argument.
Copy Operation:-
cp "$source" "$destination"
if [ $? -eq 0 ]; then
echo "File copied from $source to $destination successfully."
else
echo "Failed to copy file from $source to $destination."
Fi
Move Operation:-
mv "$source" "$destination"
if [ $? -eq 0 ]; then
echo "File moved from $source to $destination successfully."
else
echo "Failed to move file from $source to $destination."
Fi
Delete Operation:-
rm -f "$source"
if [ $? -eq 0 ]; then
echo "File $source deleted successfully."
else
echo "Failed to delete file $source."
Fi
Invalid Operation:-
echo "Error: Invalid operation specified."
Usage:-
This handles invalid operations and calls the usage function.
Usage Examples:-
Copy a File:-
./file_ops.sh copy /path/to/source.txt /path/to/destination.txt
Output:-
Code
File copied from /path/to/source.txt to /path/to/destination.txt successfully.
Move a File:-
./file_ops.sh move /path/to/source.txt /path/to/destination.txt
Output:-
Code
File moved from /path/to/source.txt to /path/to/destination.txt successfully.
Delete a File:-
./file_ops.sh delete /path/to/source.txt
Output:-
Code
File /path/to/source.txt deleted successfully.
Invalid Usage:-
./file_ops.sh copy /path/to/source.txt
Output:-
Code
Error: Destination path is required for copy operation.
Usage: ./file_ops.sh {copy|move|delete} source [destination]
Save the script to a file named file_ops.sh, make it executable, and run it
using the examples provided. This script provides a convenient way to
perform file manipulations with appropriate messages for each operation.