LA Journal-2

Download as pdf or txt
Download as pdf or txt
You are on page 1of 15

Name - Shaikh Juveria Shafi Ahmed Roll No.

- SY MSc CS 05

Practical No. - 01
Aim - Write a Simple Shell Script that Prints "Hello, Linux!" to the Terminal.
__________________________________________________________________

Theory:

A shell script is a program written for the Unix/Linux shell, which interprets and executes
commands. A simple shell script to print "Hello, Linux!" to the terminal involves writing a script
that contains a series of commands. The echo command is commonly used to display text in the
terminal, and it is key to this task. To create the script, you begin by specifying the interpreter
using a shebang (#!/bin/bash), which tells the system that the script should be run using the Bash
shell. The echo command is then used to output "Hello, Linux!" to the terminal. The script is
saved with a .sh extension, and it must be given executable permission using the chmod
command. Once this permission is granted, the script can be run from the terminal, and it will
print the desired message.

Source Code:

#!/bin/bash

echo "Hello, Linux!"

Output:

Subject - Linux Administration 1


Name - Shaikh Juveria Shafi Ahmed Roll No. - SY MSc CS 05

Practical No. - 02
Aim - Write a Script that Lists All Files in the Current Directory and
Indicates whether Each One is a File or a Directory.
__________________________________________________________________

Theory:

This script starts by using a for loop to iterate through all items in the current directory (* is a
wildcard that matches all files and directories). For each item, an if condition checks whether the
item is a directory or a file using the -d and -fflags, respectively. Depending on the result, the
script prints whether the item is a directory, file, or something else (like a symbolic link). The
script helps in identifying file types efficiently and can be expanded for more complex file
management tasks in Linux.

Source Code:

#!/bin/bash

# Loop through all items in the current directory


for item in *; do
if [ -d "$item" ]; then
echo "$item is a directory"
elif [ -f "$item" ]; then
echo "$item is a file"
else
echo "$item is neither a file nor a directory"
fi
done

Output:

Subject - Linux Administration 2


Name - Shaikh Juveria Shafi Ahmed Roll No. - SY MSc CS 05

Practical No. - 03
Aim - Develop a Script that Prompts the User to Enter their Name and Prints
a Personalized Greeting.
__________________________________________________________________

Theory:

This script begins by displaying a message asking the user to input their name using the echo
command. The read command captures the user's input and stores it in the variable name. After
the input is captured, the echo command prints a personalized greeting by referencing the
variable, integrating the user's name into the output message. This kind of script is useful for
creating interactive applications, user prompts, and basic input handling in shell environments. It
showcases the simplicity and flexibility of shell scripting for handling user interaction.

Source Code:

#!/bin/bash

# Prompt the user for their name


echo "Please enter your name:"
read name

# Print the personalized greeting


echo "Hello, $name! Welcome!"

Output:

Subject - Linux Administration 3


Name - Shaikh Juveria Shafi Ahmed Roll No. - SY MSc CS 05

Practical No. - 04
Aim - Write a Script that Compresses a Given File using Both gzip and bzip2,
Creating Two Compressed Versions.
__________________________________________________________________

Theory:

The script starts by prompting the user to enter the name of the file they wish to compress. The
read command captures the input and stores it in the variable filename. Next, the script checks if
the file exists using the -f option in the if statement. If the file is found, it is compressed using
both gzip and bzip2. The -c flag in both commands ensures that the compressed output is written
to a new file rather than replacing the original one. The compressed files will have .gz and .bz2
extensions. If the file is not found, the script informs the user to provide a valid filename.

Source Code:

#!/bin/bash

# Prompt the user for the file name


echo "Please enter the file name to compress:"
read filename

# Check if the file exists


if [ -f "$filename" ]; then
# Compress the file using gzip
gzip -k "$filename"
echo "File compressed using gzip: $filename.gz"
# Compress the file using bzip2
bzip2 -k "$filename"
echo "File compressed using bzip2: $filename.bz2"
else
echo "File does not exist. Please provide a valid file."
fi

Subject - Linux Administration 4


Name - Shaikh Juveria Shafi Ahmed Roll No. - SY MSc CS 05

Practical No. - 04
Aim - Write a Script that Compresses a Given File using Both gzip and bzip2,
Creating Two Compressed Versions.
__________________________________________________________________

Output:

Subject - Linux Administration 5


Name - Shaikh Juveria Shafi Ahmed Roll No. - SY MSc CS 05

Practical No. - 05
Aim - Create a Script that Displays the Disk Space Usage of Each Directory in
the Current Location.
__________________________________________________________________

Theory:

This script uses the du command, which calculates the disk space used by files and directories.
The -h option displays the disk usage in a human-readable format (e.g., 1K, 10M, 2G). The
--max-depth=1 option ensures that du only calculates the disk space for top-level directories in
the current location, without drilling down into subdirectories. This prevents an overwhelming
amount of detail and focuses on summarizing usage at the directory level.

Source Code:

#!/bin/bash

# Function to display disk usage recursively


display_disk_usage() {
local path=$1
local level=$2
local indent=$(printf "%${level}s" "" | tr ' ' ' ') # Indentation based on the level
# Calculate the size of the current directory
local size=$(du -sh "$path" 2>/dev/null | cut -f1)
echo "${indent}${path}: ${size}"
# Iterate over all subdirectories
for dir in "$path"*/; do
if [ -d "$dir" ]; then
display_disk_usage "$dir" $((level + 1))
fi
done
}

# Main function to execute the script


main() {
local current_directory=$(pwd)
echo "Disk usage for directories in: ${current_directory}"
display_disk_usage "$current_directory" 0
}

Subject - Linux Administration 6


Name - Shaikh Juveria Shafi Ahmed Roll No. - SY MSc CS 05

Practical No. - 05
Aim - Create a Script that Displays the Disk Space Usage of Each Directory in
the Current Location.
__________________________________________________________________

# Execute the main function


main

Output:

Subject - Linux Administration 7


Name - Shaikh Juveria Shafi Ahmed Roll No. - SY MSc CS 05

Practical No. - 06
Aim - Write a Script to Automate the Process of Creating a New Partition on
a Specified Disk.
__________________________________________________________________

Theory:

This script automates the creation of a new partition on a specified disk by using fdisk in batch
mode. The script starts by checking if it is being run with root privileges using the $EUID
variable. If not, it prompts the user to run it as root. Next, it prompts the user to enter the name of
the disk they want to partition (e.g., /dev/sda) and checks if the disk exists using the -b option in
the if statement to verify the block device. The script then passes commands to fdisk using a
heredoc syntax ((...) | fdisk $disk). The commands include:
● n: Create a new partition.
● p: Specify it as a primary partition.
● 1: Use partition number 1.
● Default values for the first and last sectors (by pressing Enter).
● w: Write the changes to the disk.

Source Code:

#!/bin/bash

# Check if the script is run with superuser privileges


if [ "$(id -u)" -ne 0 ]; then
echo "This script must be run as root. Please use 'sudo' to run the script."
exit 1
fi

# Prompt the user for the disk to partition


echo "Please enter the disk to partition (e.g., /dev/sda):"
read disk

# Check if the disk exists


if [ ! -b "$disk" ]; then
echo "The specified disk does not exist. Please check the disk name and try again."
exit 1
fi

Subject - Linux Administration 8


Name - Shaikh Juveria Shafi Ahmed Roll No. - SY MSc CS 05

Practical No. - 06
Aim - Write a Script to Automate the Process of Creating a New Partition on
a Specified Disk.
__________________________________________________________________

# Prompt the user for the partition number and size


echo "Please enter the partition number (e.g., 1 for /dev/sda1):"
read partition_number
echo "Please enter the size of the partition (e.g., 1G for 1 Gigabyte):"
read size

# Use fdisk to create a new partition


(
echo n # Add a new partition
echo p # Primary partition
echo "$partition_number" # Partition number
echo # Default first sector
echo "+$size" # Size of the partition
echo w # Write the changes
) | fdisk "$disk"

# Inform the user about the need to format the new partition
echo "The partition has been created. You need to format it before use. For example, you can
use:"
echo "mkfs.ext4 ${disk}${partition_number}"

Output:

Subject - Linux Administration 9


Name - Shaikh Juveria Shafi Ahmed Roll No. - SY MSc CS 05

Practical No. - 07
Aim - Develop a Script that Checks the Status of Essential System Services
(e.g., SSH, Apache) and Prints whether they are Running.
__________________________________________________________________

Theory:

This script starts by defining an array (services) that contains the names of essential services
such as SSH (ssh) and Apache (apache2). The for loop iterates through each service in the array,
and for each service, the systemctl is-active command is used to check if the service is active
(i.e., running). The output of this command is stored in the variable status.

Source Code:

#!/bin/bash

# List of services to check


SERVICES=("ssh" "apache2" "nginx")

# Function to check the status of a service


check_service_status() {
SERVICE_NAME=$1
if service "$SERVICE_NAME" status > /dev/null 2>&1; then
echo "$SERVICE_NAME is running."
else
echo "$SERVICE_NAME is not running."
fi
}

# Main function to loop over services and check their status


main() {
echo "Checking the status of essential services..."
for SERVICE in "${SERVICES[@]}"; do
check_service_status "$SERVICE"
done
}

# Execute the main function


main

Subject - Linux Administration 10


Name - Shaikh Juveria Shafi Ahmed Roll No. - SY MSc CS 05

Practical No. - 07
Aim - Develop a Script that Checks the Status of Essential System Services
(e.g., SSH, Apache) and Prints whether they are Running.
__________________________________________________________________

Output:

Subject - Linux Administration 11


Name - Shaikh Juveria Shafi Ahmed Roll No. - SY MSc CS 05

Practical No. - 08
Aim - Create a Script that Asks the User if they want to Shut Down
the System and Performs Accordingly.
__________________________________________________________________

Theory:

This script starts by asking the user if they want to shut down the system using the echo and read
commands. The user’s response is stored in the response variable. The if statement checks the
value of the response:
● If the user types "yes," the system will shut down immediately using the sudo shutdown
-h now command (-hstands for "halt," which powers off the system).
● If the user types "no," the script prints a message saying the shutdown is canceled and
exits.
● If the input is anything other than "yes" or "no," the script will notify the user of invalid
input and end without taking any further action.

Source Code:

#!/bin/bash

# Prompt the user for confirmation


echo "Do you want to shut down the system? (yes/no)"
read response

# Convert the response to lowercase for case-insensitive comparison


response=$(echo "$response" | tr '[:upper:]' '[:lower:]')

# Check the response and perform the appropriate action


if [ "$response" == "yes" || "$response" == "y" ]; then
echo "Shutting down the system..."
# Perform the shutdown
sudo shutdown -h now
elif [ "$response" == "no" ]; then
echo "Shutdown canceled."
else
echo "Invalid response. Please enter 'yes' or 'no'."
fi

Subject - Linux Administration 12


Name - Shaikh Juveria Shafi Ahmed Roll No. - SY MSc CS 05

Practical No. - 08
Aim - Create a Script that Asks the User if they want to Shut Down
the System and Performs Accordingly.
__________________________________________________________________

Output:

Subject - Linux Administration 13


Name - Shaikh Juveria Shafi Ahmed Roll No. - SY MSc CS 05

Practical No. - 09
Aim - Write a Script that Generates a SSH Key Pair and Provides
Instructions for Adding the Public Key to the authorized_keys File.
__________________________________________________________________

Theory:

This script automates the process of generating an SSH key pair using the ssh-keygen command.
The key pair consists of a private key (stored in ~/.ssh/id_rsa) and a public key (stored in
~/.ssh/id_rsa.pub). The -t rsa option specifies that an RSA key should be generated, and the -b
4096 option defines the key size as 4096 bits for stronger encryption. The -N "" option specifies
an empty passphrase, meaning the private key is not encrypted with a passphrase. If a passphrase
is preferred, the user can remove the -N "" part, and the script will prompt for one. Once the key
pair is generated, the script provides instructions for adding the public key to the
authorized_keys file on the remote server. It suggests using the ssh-copy-id command, which
automates the process of copying the public key to the server. Alternatively, it guides the user to
manually copy the contents of the public key (id_rsa.pub) to the ~/.ssh/authorized_keys file on
the server, explaining how to view the public key using the cat command.

Source Code:

#!/bin/bash

# Function to generate SSH key pair


generate_ssh_key() {
# Prompt for email to use in the SSH key (optional, used as a comment)
echo "Enter your email for the SSH key comment (optional):"
read EMAIL
# Generate the SSH key pair
ssh-keygen -t rsa -b 4096 -C "$EMAIL" -f ~/.ssh/id_rsa
echo "SSH key pair generated successfully."
}

# Check if SSH key already exists


if [ -f ~/.ssh/id_rsa ]; then
echo "SSH key already exists at ~/.ssh/id_rsa"
else
# Generate a new SSH key pair
generate_ssh_key
fi

Subject - Linux Administration 14


Name - Shaikh Juveria Shafi Ahmed Roll No. - SY MSc CS 05

Practical No. - 09
Aim - Write a Script that Generates a SSH Key Pair and Provides
Instructions for Adding the Public Key to the authorized_keys File.
__________________________________________________________________

# Provide instructions for adding the public key to authorized_keys


echo ""
echo "To use this SSH key for remote login, follow these steps:"
echo "1. Copy the public key to the remote server: ssh-copy-id user@remote_host "
echo ""
echo "2. Alternatively, manually copy the public key using the following command:"
echo " cat ~/.ssh/id_rsa.pub | ssh user@remote_host 'mkdir -p ~/.ssh && cat >>
~/.ssh/authorized_keys'"
echo "3. Once the key is added, you can connect to the remote host using: ssh
user@remote_host"

Output:

Subject - Linux Administration 15

You might also like