Unit4 - Subjective Questions
CSC104 • Practice Questions with Detailed Answers
Explain the concept of multi-function scripting in Bash. How does breaking a script into functions improve maintainability?
Multi-function scripting involves structuring a Bash script into discrete, reusable blocks of code called functions, rather than writing a single linear list of commands.
Key Benefits:
- Modularity: Large scripts are broken down into manageable tasks (e.g.,
install_package,update_config,restart_service). - Reusability: A function can be called multiple times within the script without rewriting the code.
- Readability: It makes the main execution logic clearer by abstracting details.
- Debugging: Errors can be isolated to specific functions easier than debugging a monolithic script.
Syntax Example:
bash
function_name () {
commands
}
Write a snippet of code to create an interactive menu in Bash using a case statement. Explain how to colorize the output text to make it user-friendly.
To create an interactive menu, we typically use a while loop combined with read and case. To add colors, we use ANSI escape codes (e.g., \e[31m for red, \e[0m to reset).
Code Snippet:
bash
!/bin/bash
RED='\033[0;31m'
GREEN='\033[0;32m'
NC='\033[0m' # No Color
show_menu() {
echo -e "{NC}"
echo -e "{NC}"
}
read -p "Enter choice: " choice
case $choice in
1) echo "You picked One" ;;
2) echo "You picked Two" ;;
*) echo -e "{NC}" ;;
esac
Explanation: The echo -e flag enables the interpretation of backslash escapes for colors. The case statement handles the logic based on user input.
Distinguish between Pipes (|) and Redirection (>, >>, <) in Bash scripting with examples.
Pipes (|) and Redirection handle data flow differently:
- Pipes (
|): Connect the standard output (stdout) of one command to the standard input (stdin) of another command.- Example:
cat access.log | grep "404"(Sends the file content to grep).
- Example:
- Redirection (
>,>>): Directs the output of a command to a file (or device) or input from a file.- Overwrite (
>):echo "Hello" > file.txt(Replaces content). - Append (
>>):echo "World" >> file.txt(Adds to the end). - Input (
<):mysql -u root -p < db_dump.sql(Reads input from file).
- Overwrite (
Summary: Pipes connect process to process; Redirection connects process to file.
Describe two methods to achieve remote script execution over SSH. How can you run a local script on a remote server without copying the file first?
Running scripts on remote servers is essential for automation.
Method 1: Execute a command directly
bash
ssh user@hostname "command_to_run"
Method 2: Execute a local script remotely (stdin)
To run a script that exists on your local machine on a remote server without manually copying it using scp first, pipe the script into ssh:
bash
ssh user@hostname 'bash -s' < local_script.sh
Explanation: The < operator redirects the local file into the ssh command, and 'bash -s' tells the remote shell to read commands from standard input.
What is jq? Explain how it is used to parse JSON data in Bash scripts with an example of extracting a specific value.
jq is a lightweight, flexible command-line JSON processor. Since Bash treats text linearly, handling the structured, nested nature of JSON is difficult with standard tools like grep or awk. jq allows slicing, filtering, and mapping JSON data.
Example:
Suppose we have a JSON object representing a user:
{"name": "Alice", "role": "admin"}
Extraction Command:
bash
echo '{"name": "Alice", "role": "admin"}' | jq -r '.name'
Result: Alice
Explanation: The . represents the root object, and .name accesses the value of the key "name". The -r flag outputs raw strings without quotes.
Explain the significance of Cloudflare API integration in automation. Which command-line tool is primarily used for this, and what HTTP headers are typically required?
Cloudflare API integration allows system administrators to automate DNS management, clear caches, and configure firewall rules programmatically without using the web dashboard. This is crucial for dynamic environments where IP addresses change (DDNS) or for automated deployment pipelines.
Tool: The primary tool used is curl.
Required Headers:
To authenticate and interact with the API, requests generally require:
- Content-Type: Usually
application/json. - Authorization: This can be an API Token (
Authorization: Bearer <TOKEN>) or a combination of Email (X-Auth-Email) and Global API Key (X-Auth-Key).
Example Request:
bash
curl -X GET "https://api.cloudflare.com/client/v4/user/tokens/verify" \
-H "Authorization: Bearer <YOUR_TOKEN>" \
-H "Content-Type: application/json"
Design the logic for an Access Log Summarizer script. Which tools would you use to count the top 5 IP addresses hitting a web server?
An Access Log Summarizer analyzes web server logs (e.g., Nginx or Apache) to provide insights into traffic.
Logic Flow:
- Read the file: Input the log file (usually
/var/log/nginx/access.log). - Extract IPs: Filter out the specific column containing the IP address.
- Sort: Group identical IPs together.
- Count: Count the occurrences of unique IPs.
- Sort by Frequency: Order them numerically in descending order.
- Limit: Head the top 5 results.
Tools & Command:
We use awk, sort, uniq, and head.
bash
awk '{print $1}' access.log | sort | uniq -c | sort -nr | head -5
awk '{print $1}': Prints the first column (IP).uniq -c: Counts occurrences (requires sorted input).sort -nr: Sorts numerically, reverse order.
How can SSMTP be used to send automated email alerts from a Bash script? Describe the basic configuration required in /etc/ssmtp/ssmtp.conf.
SSMTP is a simple Mail Transfer Agent (MTA) that forwards emails from a local machine to a configured SMTP mail hub (like Gmail or Outlook). It allows Bash scripts to send alerts (e.g., "Disk Full", "Backup Failed") easily.
Configuration (/etc/ssmtp/ssmtp.conf):
You must define the mail hub and authentication credentials.
root=your_email@gmail.com(Who gets root's mail)mailhub=smtp.gmail.com:587(The SMTP server and port)AuthUser=your_email@gmail.comAuthPass=your_app_passwordUseSTARTTLS=YES(For security)
Usage in Script:
bash
echo "Body text" | ssmtp recipient@example.com
Or with a subject:
bash
{
echo "Subject: Alert";
echo "Something happened.";
} | ssmtp user@example.com
Write a Bash one-liner or short script logic to create a secure Password Generator. Explain the source of randomness used.
A secure password generator relies on a source of high-entropy randomness to ensure passwords cannot be guessed.
Source of Randomness:
We typically use /dev/urandom. It is a special file in Linux that serves as a pseudorandom number generator.
Bash One-Liner:
bash
< /dev/urandom tr -dc _A-Z-a-z-0-9 | head -c${1:-16}; echo;
Detailed Explanation:
< /dev/urandom: Feeds random raw data into the command.tr -dc _A-Z-a-z-0-9: Thetr(translate) command with-d(delete) and-c(complement) keeps only the characters specified (alphanumeric plus underscore) and deletes everything else (garbage bytes).head -c${1:-16}: Takes the first 16 characters (or a length passed as an argument) of the clean stream.echo: Adds a newline for formatting.
Outline the steps required to script an Automated WordPress setup on a LAMP stack. What are the four main components involved?
Automating a WordPress installation involves configuring the LAMP stack (Linux, Apache, MySQL/MariaDB, PHP) and downloading WordPress.
The 4 Components:
- Linux: The OS (already present).
- Apache: The web server.
- MySQL: The database backend.
- PHP: The scripting language WordPress is written in.
Automation Steps:
- Install Packages:
apt install apache2 mariadb-server php libapache2-mod-php php-mysql. - Configure Database: Script MySQL to create a DB, User, and grant privileges.
- Example:
mysql -e "CREATE DATABASE wp; GRANT ALL ON wp.* TO 'user'@'localhost' IDENTIFIED BY 'pass';"
- Example:
- Download WordPress: Use
wgetto get the latest tarball andtarto extract it to/var/www/html. - Configure Permissions:
chown -R www-data:www-data /var/www/html/wordpress. - Create Config: Copy
wp-config-sample.phptowp-config.phpand usesedto inject the database credentials.
In multi-function scripting, what is the difference between local and global variables? Why is using local recommended inside functions?
In Bash, by default, variables are global, meaning a variable defined inside a function can be accessed and modified anywhere else in the script.
Distinction:
- Global Variables: Accessible throughout the entire script. If a function changes a global variable, the change persists after the function ends.
- Local Variables: Defined using the
localkeyword inside a function. They are only visible within that function.
Why use local?
It prevents namespace pollution and unintended side effects. If two different functions use a variable named $i (e.g., for a loop) without declaring it local, calling one function might reset the loop counter of the other, causing infinite loops or logic errors. Using local ensures the function is self-contained.
When parsing API responses with jq, how would you extract specific values from a JSON array? Assume the input is [{"id":1}, {"id":2}].
JSON arrays are ordered lists of values enclosed in square brackets []. In jq, you access array elements using their index (starting at 0) or iterate over them.
Input: [{"id":1}, {"id":2}]
Method 1: Extract a specific index
To get the first item's ID:
bash
... | jq '.[0].id'
Output: 1
Method 2: Iterate over all elements
To get all IDs:
bash
... | jq '.[].id'
Output:
1
2
Explanation: [] without an index creates an iterator that runs the subsequent filter (.id) against every object in the array.
Explain the role of Standard Error (stderr) redirection. How do you redirect both output and errors to the same file?
In Linux, there are three standard streams: Standard Input (0), Standard Output (1), and Standard Error (2). Normal output goes to stdout, while error messages go to stderr. By default, both print to the screen.
Role of Stderr:
It ensures that error messages are separated from valid data. This allows a user to pipe valid data to another program while still seeing errors on the screen, or log errors separately.
Redirecting Both (2>&1):
To capture everything in one file, you must redirect file descriptor 2 (stderr) to file descriptor 1 (stdout), and then redirect stdout to the file.
Syntax:
bash
command > logfile.txt 2>&1
This reads as: "Send stdout to logfile.txt, and send stderr to wherever stdout is currently going."
In the context of Cloudflare API integration, what is the difference between updating a DNS record via POST vs PUT (or PATCH)?
When interacting with RESTful APIs like Cloudflare's:
- POST: typically used to create a new resource. In Cloudflare, you use POST to create a new DNS record that didn't exist before.
- PUT: Used to replace an existing resource entirely. You must provide the complete data set for the record. If you omit a field, it might be set to null/default.
- PATCH: Used to modify part of an existing resource. You only send the fields you want to change (e.g., changing the IP address but keeping the TTL and Proxy status the same).
Automation Context: A script meant to update a dynamic IP (DDNS) usually first checks if the record exists (GET). If it does, it uses PUT/PATCH to update the IP. If it doesn't, it uses POST to create it.
Derive a command using awk and grep for an Access Log Summarizer that specifically counts the number of "404 Not Found" errors in a log file.
To count specific HTTP status codes like 404, we need to filter lines containing the code and then count them.
Approach:
- Grep: Filter lines that contain the string " 404 " (spaces ensure we don't match 404 in a timestamp or IP).
- Count: Use
wc -l(word count lines).
Command:
bash
grep " 404 " /var/log/nginx/access.log | wc -l
Alternative using pure awk (More robust):
Assumes the status code is in the 9th column (standard format).
bash
awk '$9 == "404" {count++} END {print count}' /var/log/nginx/access.log
This awk command checks if the 9th field strictly equals 404, increments a counter, and prints the total at the end.
Discuss the security implications of storing passwords in scripts for Automated WordPress setup or SSMTP. How can this be mitigated?
Hardcoding passwords in scripts (for MySQL, Cloudflare API tokens, or Email Auth) poses a severe security risk. If the script is shared, committed to version control (git), or read by unauthorized users, the credentials are compromised.
Mitigation Strategies:
- Environment Variables: Store secrets in variables (
export DB_PASS='secret') outside the script and reference them ($DB_PASS). - Configuration Files: Read from a separate, restricted file (e.g.,
source /etc/secret_config.sh) that has strict file permissions (chmod 600). - Prompting: Use
read -sto ask the user for the password at runtime so it is never stored on disk. - Secrets Management: In advanced setups, use tools like HashiCorp Vault or verify usage via SSH keys instead of passwords where possible.
Explain how the select loop differs from the while loop when creating an interactive menu in Bash.
while loop: A general-purpose loop. To create a menu, you manually echo the options, use read to get input, and validate it. It offers full control over the layout but requires more code.
select loop: A Bash construct specifically designed for generating menus.
- It automatically prints a numbered list of options based on the provided arguments.
- It prompts the user with
PS3(prompt string). - It loops automatically until a
breakcommand is issued.
Example of select:
bash
PS3="Choose an option: "
select opt in "Option 1" "Option 2" "Quit"; do
case $opt in
"Option 1") echo "You chose 1" ;;
"Quit") break ;;
*) echo "Invalid" ;;
esac
done
When using Remote script execution, how do you handle variables? Specifically, explain the difference between $VAR and $VAR when executing a command over SSH.
When running commands over SSH, variable expansion depends on whether the variable should be evaluated on the local machine (before sending) or the remote machine (during execution).
Scenario: ssh user@host "echo $PATH"
-
Double Quotes (
"...") - Local Expansion:ssh user@host "echo $PATH"- Bash on the local machine replaces
$PATHwith the local path. The remote server just echoes that string.
-
Escaping (
$) or Single Quotes ('...') - Remote Expansion:ssh user@host "echo $PATH"ORssh user@host 'echo $PATH'- The local shell ignores the variable. The literal string
$PATHis sent to the remote server. The remote shell expands it, showing the remote path.
Conclusion: Use $ or single quotes if you need the variable to reflect the state of the remote server.
In a Password Generator script, why is string manipulation (like fold or tr) necessary after reading from /dev/urandom?
/dev/urandom outputs a stream of raw binary bytes. This includes printable characters, but also non-printable control characters, null bytes, and extended ASCII codes which are not suitable for standard text passwords.
Necessity of Manipulation:
- Filtering (
tr): We must filter the stream to keep only safe characters (letters, numbers, specific symbols) usingtr -dc 'set'. - Formatting (
fold/head): The stream is continuous (infinite). commands likefold -w 16(wrap width) orhead -c 16are required to cut the infinite stream into a usable string length.
Without these tools, the output would be a binary mess that could crash a terminal or be unusable as a password.
Describe the specific database automation commands required during an Automated WordPress setup. How do you ensure the WordPress script can access the database?
Database automation is done using the mysql (or mariadb) command-line client passed with the -e (execute) flag.
Required Commands:
- Create Database: Container for WP data.
CREATE DATABASE wordpress_db; - Create User: A specific user for security (don't use root).
CREATE USER 'wp_user'@'localhost' IDENTIFIED BY 'strong_password'; - Grant Privileges: Allow the user to modify the database.
GRANT ALL PRIVILEGES ON wordpress_db.* TO 'wp_user'@'localhost'; - Flush:
FLUSH PRIVILEGES;
Ensuring Access:
In the Bash script, after running the SQL commands, you must update the wp-config.php file (usually using sed) to match the values created above:
DB_NAMEwordpress_dbDB_USERwp_userDB_PASSWORDstrong_password