1. Manage Files
Question 1: How do you find and remove large files that are no longer needed to free up space in a specific directory?
Answer: To find and remove large files within a directory, I use the find command combined with xargs and rm. For example, to find files larger than 100MB in /var/log and remove them, I'd use:
find /var/log -type f -size +100M -print0 | xargs -0 rm -f
This command finds files larger than 100MB in /var/log and then removes them securely using xargs to handle filenames with special characters.
Question 2: Describe how you would synchronize files from one server to another in real-time.
Answer: For real-time file synchronization, I recommend using rsync in combination with a file watching tool like inotify. For continuous sync, lsyncd (Live Syncing Daemon) is an excellent tool that combines rsync and inotify. It monitors directories for changes and synchronizes the changes in real time. The setup involves configuring lsyncd with a configuration file to specify source and target directories, and optionally including ssh options for remote sync.
Question 3: How do you ensure case-insensitive file searches in a case-sensitive filesystem?
Answer: To perform case-insensitive file searches on a case-sensitive filesystem, use the find command with the -iname option. For example, to find a file named sample.txt without considering case, I'd use:
find /path/to/search -type f -iname "sample.txt"
This command will match sample.txt, Sample.txt, SAMPLE.TXT, etc.
Question 4: How would you recover deleted files in a Linux system?
Answer: Recovering deleted files can be tricky and depends on the filesystem and the state of the disk. Tools like testdisk or extundelete can be used for recovery. For example, to recover files from an ext4 filesystem, extundelete can be used:
extundelete /dev/sda1 --restore-all
This assumes /dev/sda1 is the partition where files were deleted. It's critical to mount the filesystem as read-only or work from a live CD to avoid overwriting deleted data.
Question 5: Explain how to find the difference between two directories.
Answer: To compare the contents of two directories, diff can be used:
diff -rq directory1 directory2
This command recursively (-r) compares files in both directories and quietly (-q) reports only when files differ. It's useful for checking synchronization states or verifying backups.
Question 6: How do you automate the backup of a directory to a remote server?
Answer: For automating backups, I use rsync over SSH for secure transfer, combined with a cron job for scheduling. Here's a cron job example that backs up /home/data to a remote server daily at midnight:
0 0 * * * rsync -avz /home/data user@remote-server:/backup/data
This cron entry uses rsync with archive mode (-a), compression (-z), and verbose output (-v) to synchronize the /home/data directory to the remote server.
2. Work with Text Files
Question 1: How would you find and replace a specific string in multiple files within a directory?
Answer: To find and replace a specific string in multiple files, I use sed with a combination of find and xargs. For example, to replace "oldtext" with "newtext" in .txt files, I'd execute:
find /path/to/files -type f -name "*.txt" -print0 | xargs -0 sed -i 's/oldtext/newtext/g'
This command searches for .txt files and uses sed to replace "oldtext" with "newtext" in-place (-i) globally within each file (g).
Question 2: How do you count the number of lines, words, and characters in a text file?
Answer: The wc (word count) command is used to count lines, words, and characters. For example:
wc filename.txt
This will output the number of lines, words, and characters in filename.txt. To get just the line count, you can use wc -l filename.txt.
Question 3: Explain how to sort a text file by the second column in descending order.
Answer: To sort a text file by the second column in descending order, use the sort command:
sort -k2,2 -r filename.txt
Here, -k2,2 specifies the second column as the sort key, and -r sorts in reverse (descending) order.
Question 4: How can you remove duplicate lines in a file while preserving the original order?
Answer: To remove duplicate lines while preserving the original order, awk can be very effective:
awk '!visited[$0]++' filename.txt > output.txt
This awk command keeps track of lines seen in an associative array visited and only prints lines that have not been seen before, preserving their first occurrence's order.
Question 5: How do you extract all IP addresses from a log file and list them uniquely?
Answer: To extract and list unique IP addresses from a log file, grep and sort commands can be combined:
grep -oP '(\d{1,3}\.){3}\d{1,3}' log_file.txt | sort -u
This uses grep with Perl-compatible regular expressions (-P) to match IP addresses and outputs only the matched part (-o). Then, sort -u sorts the results and ensures uniqueness.
Question 6: Describe a way to convert a CSV file to a JSON format in Linux.
Answer: While there are many tools for this, using jq in combination with awk is a powerful approach. Assuming a simple CSV without embedded commas:
awk -F',' '{print "{\"column1\":\"" $1 "\",\"column2\":\"" $2 "\"}"}' file.csv | jq . > file.json
This awk command formats each line as JSON, and jq ensures the JSON is valid and nicely formatted. For more complex CSVs, tools like csvtojson are more robust and handle edge cases.
Question 7: How do you combine multiple text files into one and remove any lines that contain a specific word?
Answer: To combine and filter files, use cat and grep:
cat file1.txt file2.txt file3.txt | grep -v "specificword" > combined.txt
This concatenates the files and pipes the output to grep -v, which removes lines containing "specificword," and the result is redirected to combined.txt.
3. Log in and Run Tasks with Administrator Privileges
Question 1: Explain how you would run a script as another user without sharing that user's password.
Answer: To run a script as another user without sharing the user's password, I'd configure sudo to allow execution of the script as the target user. This involves editing the sudoers file using visudo to add a rule like:
yourusername ALL=(targetuser) NOPASSWD: /path/to/script.sh
This allows yourusername to run /path/to/script.sh as targetuser without a password. To execute the script, you'd then use:
sudo -u targetuser /path/to/script.sh
Question 2: How do you securely get root privileges for a series of commands without logging in as root directly?
Answer: To securely gain root privileges for a series of commands without logging in as root, I use sudo -s or sudo -i. This grants a shell with root privileges, where subsequent commands are executed as root. It's secure because it logs all commands executed with sudo, offering traceability and accountability.
Question 3: Describe how to give a specific user the ability to run only a specific command as root.
Answer: To grant a specific user the ability to run only a specific command as root, edit the sudoers file with visudo and add a line like:
username ALL=(ALL) NOPASSWD: /path/to/command
This configuration allows username to execute /path/to/command as root without entering a password, but restricts all other commands.
Question 4: How do you preserve the environment variables when running a sudo command?
Answer: To preserve environment variables when running a sudo command, use the -E option with sudo. For example:
sudo -E /path/to/command
This passes the current user's environment variables to the sudo environment, which is useful for scripts that depend on user-specific variables.
Question 5: In a situation where sudo is not available, how can you switch to the root user?
Answer: If sudo is not available, and you have the root password, you can switch to the root user using su (substitute user) by simply typing su and entering the root password when prompted. This switches the current session to a root shell:
su -
The - option provides an environment similar to what the root user would expect.
Question 6: Explain how to configure sudo timeouts to extend the duration a user remains sudo after entering their password.
Answer: To configure sudo timeouts, you edit the sudoers file using visudo and set the timestamp_timeout value. For example, to extend the duration to 30 minutes:
Defaults timestamp_timeout=30
This setting allows a user to re-use their sudo session without re-entering the password for 30 minutes after the initial password entry.
Question 7: How do you manage a situation where you need to run a graphical application as root?
Answer: To run a graphical application as root, gksudo, gksu, or pkexec can be used. For systems where these are not available or recommended, configuring policykit or using sudo with the -H option (to set the home directory to root's home directory) is an alternative. For example, with sudo -H:
sudo -H gedit /etc/configfile
This command ensures that any configuration files or temporary files created by the graphical application are owned by root, reducing the risk of permission issues.
Question 8: How can you list all commands a specific user is allowed to run with sudo?
Answer: To list all commands a specific user is allowed to run with sudo, you can use the sudo -l command. When executed by a superuser, it can be used to see the sudo privileges of another user:
sudo -l -U username
This command displays the rules from the sudoers file that apply to the specified user, detailing the commands they're permitted to run.
Question 9: Describe a method to temporarily increase the verbosity of sudo logging for troubleshooting purposes.
Answer: To temporarily increase the verbosity of sudo logging, you can edit the sudoers file using visudo and set the log_output directive for specific commands or users. Additionally, adjusting the Defaults entry for logfile and log_level can increase logging detail:
Defaults log_level=debug
This change directs sudo to log more detailed information, aiding in troubleshooting. Remember to revert the settings after resolving the issue to avoid excessive logging.
Question 10: How would you ensure that a script executed with sudo cannot be modified by non-root users?
Answer: To ensure a script executed with sudo cannot be modified by non-root users, you must set the ownership to root and restrict write permissions to the owner only. Use chown and chmod commands:
sudo chown root:root /path/to/script.sh
sudo chmod 755 /path/to/script.sh
This configuration allows only root (or users with sudo privilege) to modify the script, while others can only execute or read it, enhancing security.
Question 11: Explain the risks and mitigation strategies of allowing users to execute commands as root with no password.
Answer: Allowing users to execute commands as root with no password poses security risks, such as unauthorized system changes, potential exposure to malicious actions, and the risk of accidental system damage. Mitigation strategies include:
Limit Usage: Only allow no-password root access for specific, low-risk commands.
Auditing and Monitoring: Use auditd or similar tools to monitor and log sudo usage, enabling traceability of actions performed with elevated privileges.
Regular Reviews: Periodically review the sudoers file and audit logs to ensure only appropriate permissions are granted and used responsibly.
Question 12: How do you delegate a complex command sequence to be run as root without giving full root access?
Answer: To delegate a complex command sequence without full root access, encapsulate the sequence in a script, secure the script as described previously (ownership to root, restrict write permissions), and grant specific sudo privileges for that script. This method confines the elevated privileges to a controlled, auditable context.
Question 13: What are the considerations when using sudo in automated scripts or cron jobs?
Answer: When using sudo in automated scripts or cron jobs, consider the following:
Non-interactive Mode: Ensure commands can run without requiring a password prompt. This may involve configuring specific NOPASSWD entries in the sudoers file.
Secure Path: Use absolute paths for commands and scrutinize environmental variables to prevent path hijacking.
Error Handling: Implement robust error handling to manage potential failures gracefully, preventing partial execution with elevated privileges.
Question 14: How can you restrict sudo users from launching interactive shells?
Answer: To restrict sudo users from launching interactive shells, you can use the NOEXEC tag in the sudoers file for commands like bash, sh, or other shell programs. This prevents users from starting a new shell with elevated privileges:
username ALL=(ALL) NOEXEC: /bin/bash, /bin/sh
This setup allows execution of specified commands but prevents spawning interactive shells, tightening security.
4. Work with the Bash Shell
Question 1: Explain how to create a Bash script that takes input arguments and prints a greeting message using those arguments.
Answer: To create a Bash script that accepts input arguments and uses them to print a greeting message, you can use the following example:
#!/bin/bash
# Script to print a greeting message using input arguments
echo "Hello, $1! Welcome to $2."
Save this script as greet.sh, make it executable with chmod +x greet.sh, and run it with two arguments like ./greet.sh John "the DevOps world".
Question 2: Describe a way to check if a file exists and is readable in a Bash script, and print a message based on the check.
Answer: To check if a file exists and is readable, you can use an if statement with -f and -r flags in a Bash script:
#!/bin/bash
# Script to check if a file exists and is readable
if [ -f "$1" ] && [ -r "$1" ]; then
echo "File $1 exists and is readable."
else
echo "File $1 does not exist or is not readable."
fi
Run this script with the filename as an argument to perform the check.
Question 3: How can you extract the extension of a filename passed as an argument to a Bash script?
Answer: To extract the extension of a filename in a Bash script, you can use parameter expansion:
#!/bin/bash
# Script to extract file extension
filename=$1
extension="${filename##*.}"
echo "The extension of $filename is $extension."
This script takes a filename as an argument and prints its extension.
Question 4: Write a Bash one-liner that lists all directories in the current directory.
Answer: A Bash one-liner to list all directories in the current directory is:
ls -d */ | cut -f1 -d'/'
This uses ls to list directories (-d */), and cut removes the trailing slash from each directory name.
Question 5: Explain how to loop through files with a specific extension in a directory and print their names in a Bash script.
Answer: To loop through files with a specific extension and print their names, you can use a for loop in a Bash script:
#!/bin/bash
# Script to loop through and print names of .txt files
for file in *.txt; do
echo "Found text file: $file"
done
This script iterates over all .txt files in the current directory and prints their names.
Question 6: How would you use Bash to redirect the output of a command to a file, appending it without overwriting the existing contents?
Answer: To append the output of a command to a file without overwriting its existing contents, use the >> operator:
echo "New line of text" >> existingfile.txt
This appends "New line of text" to existingfile.txt.
Question 7: Describe how to compare two text files and print the lines that are different in Bash.
Answer: To compare two text files and print the differing lines, you can use the diff command in Bash:
diff file1.txt file2.txt
diff prints the lines that differ between file1.txt and file2.txt.
Question 8: How can you create a Bash alias that makes it easier to navigate to a frequently used directory?
Answer: To create a Bash alias for navigating to a frequently used directory, add the following line to your .bashrc or .bash_profile file:
alias godir='cd /path/to/frequently/used/directory'
After adding the alias, run source ~/.bashrc (or source ~/.bash_profile), and then you can simply type godir to navigate to the specified directory.
Question 9: Write a Bash command using awk to sum the numbers in the first column of a text file and print the result.
Answer:
awk '{sum += $1} END {print sum}' filename.txt
This awk command reads filename.txt, accumulates the values of the first column in the variable sum, and prints the sum after processing all lines.
Question 10: Describe how to use sed to replace every occurrence of the string 'http' with 'https' in a file named urls.txt, modifying the file in-place.
Answer:
sed -i 's/http/https/g' urls.txt
This command uses sed with the -i (in-place) option to replace all instances of "http" with "https" within urls.txt.
Question 11: Explain how to process exit statuses in Bash scripts to perform different actions based on the success or failure of a command.
Answer: In Bash, you can use the $? variable to get the exit status of the last executed command, then use an if-else statement to branch your script's logic:
#!/bin/bash
# Example script to check command exit status
command_to_run
if [ $? -eq 0 ]; then
echo "Command succeeded."
else
echo "Command failed."
fi
This script runs command_to_run, then checks its exit status. If the command succeeded (exit status 0), it prints a success message; otherwise, it prints a failure message.
Question 12: Use awk to print every third line starting from the first line of a file named input.txt.
Answer:
awk 'NR % 3 == 1' input.txt
This awk command prints every line of input.txt where the line number modulo 3 equals 1, effectively printing every third line starting from the first.
Question 13: How can you use sed to delete lines 5 through 10 in a text file without making changes to the original file?
Answer:
sed '5,10d' originalfile.txt > newfile.txt
This sed command deletes lines 5 through 10 in originalfile.txt, redirecting the output to newfile.txt, thus leaving the original file unchanged.
Question 14: Describe a scenario where a Bash script fails due to an unhandled error in a pipeline and how to troubleshoot it using set -e and set -o pipefail.
Answer: In a Bash script, if a command in a pipeline fails but the last command succeeds, the script may not exit as expected. Using set -e makes the script exit on any error, and set -o pipefail causes the pipeline to return the exit status of the first command to fail:
#!/bin/bash
set -e
set -o pipefail
command1 | command2 | command3
If any of the commands in the pipeline fails, the script will exit immediately, making it easier to identify and troubleshoot the failing part of the pipeline.
Question 15: How do you use awk and sed together in a Bash script to process a file and then modify it based on certain conditions?
Answer: Here's an example Bash script snippet that uses awk to process a file, then sed to modify it based on a condition:
#!/bin/bash
# Use awk to check condition and sed to modify the file
awk_condition_result=$(awk '/pattern/ {print $0}' input.txt)
if [[ ! -z "$awk_condition_result" ]]; then
sed -i 's/oldtext/newtext/g' input.txt
fi
This script uses awk to search for a pattern in input.txt. If the pattern is found (the result is not empty), it uses sed to replace "oldtext" with "newtext" in the file.
Question 16: You've noticed that a Bash script intended to process log files occasionally misses updates on rapidly changing files. How would you modify the script to handle real-time updates more effectively?
Answer: For handling real-time updates in log files, consider using tail -f to follow the log output in combination with awk for processing, ensuring that new lines are processed as they are written. Additionally, implementing a more robust logging system that includes message queues or pub/sub mechanisms could mitigate issues with rapid updates.
tail -f /path/to/logfile | awk '/pattern/ { action }'
This command uses tail -f to continuously monitor a logfile, piping its output to awk for real-time processing based on specified patterns and actions.
Question 17: A script using sed to modify configuration files is failing silently, leaving no clues about the issue. What steps would you take to troubleshoot and resolve this?
Answer: To troubleshoot a silently failing sed script:
Verbose Mode: Temporarily add set -x at the beginning of the script to print each command and its arguments as they are executed.
Error Handling: Introduce set -e to make the script exit on errors, helping identify the failing point.
Check sed Syntax: Verify the sed commands are syntactically correct and appropriate for the input files. Test the sed commands outside the script to ensure they perform as expected.
Permissions: Ensure the script has the necessary permissions to read and write the configuration files.
Backup Files: Use sed -i.bak to create backup copies before in-place editing, which can help diagnose issues by comparing before and after states.
Question 18: An awk command in a script is supposed to parse a CSV file and calculate sums, but it's returning incorrect totals for some rows. What could be the problem, and how would you fix it?
Answer: Incorrect totals from an awk command could stem from improper field recognition, especially in CSV files where commas within quoted fields can mislead field separation. To address this:
Use awk's -F option with a more precise field separator that accounts for CSV quoting, or
Preprocess the CSV with sed or another tool to normalize or remove internal commas within fields.
For complex CSV parsing, consider using tools designed for CSVs, like csvkit, or languages with robust CSV libraries, such as Python.
Question 19: A Bash script uses sed for in-place editing on a configuration file, but changes are not persisting across system reboots. What's likely happening, and how can you ensure changes are permanent?
Answer: If changes are not persisting across reboots, the script may be modifying a copy of the configuration file or a version that gets overwritten by default settings during boot. To ensure permanence:
Verify the script targets the correct file used by the system at runtime.
Check for any system services or startup scripts that might restore configuration files from defaults. Adjust these services or utilize them to apply your changes.
Question 20: You're using awk to extract and report metrics from application logs. However, the output is sometimes empty despite known log entries matching the criteria. What troubleshooting steps can you take?
Answer: For intermittent issues with awk processing:
Confirm Log Format: Ensure the log format hasn't changed, affecting your awk pattern matching.
Regular Expressions: Double-check the regular expressions used in awk for accuracy and specificity.
Field Delimiters: Verify the field delimiter (-F option in awk) matches the log file's structure. Log entries with inconsistent delimiters can lead to missed matches.
Test in Segments: Break down the awk command into smaller segments or test it on a subset of log entries to ensure each part functions as expected.
5. Manage Users and Groups
1. How do you create a new user in Linux?
Answer: Use the useradd command followed by the username. To add a user with a home directory, use useradd -m username.
2. How can you change a user's password in Linux?
Answer: Use the passwd command followed by the username, for example, passwd username. You'll be prompted to enter a new password.
3. How do you delete a user, but keep their home directory?
Answer: Use the userdel command with the username. To keep the home directory, omit the -r option, for example, userdel username.
4. How can you create a new group in Linux?
Answer: Use the groupadd command followed by the group name, for example, groupadd mygroup.
5. How do you add a user to a group?
Answer: Use the usermod -aG groupname username command to add a user to a group without removing them from their current groups.
6. How can you list all groups a user is a member of?
Answer: Use the groups username or id -nG username command to list all groups a user belongs to.
7. How do you change the primary group of a user?
Answer: Use the usermod -g groupname username command to change the primary group of a user.
8. How can you delete a group in Linux?
Answer: Use the groupdel command followed by the group name, for example, groupdel mygroup.
9. How do you lock and unlock a user account?
Answer: Use usermod -L username to lock and usermod -U username to unlock a user account.
10. How can you change a user's shell in Linux?
Answer: Use the chsh -s /path/to/shell username command to change the user's login shell.
11. How do you find the user ID (UID) of a user?
Answer: Use the id -u username command to find the UID of a user.
12. How can you change a user's username?
Answer: Use the usermod -l newUsername oldUsername command to change a user's username.
13. How do you create a user with a specific UID and GID?
Answer: Use useradd -u UID -g GID username to create a user with a specific UID and primary GID.
14. How can you show all users on the system?
Answer: Use cat /etc/passwd to list all users. For a simpler list, use cut -d: -f1 /etc/passwd.
15. How do you restrict a user from logging in?
Answer: Set the user's shell to /usr/sbin/nologin using usermod -s /usr/sbin/nologin username.
16. How can you add a user with a custom home directory?
Answer: Use useradd -m -d /path/to/home username to create a user with a specified home directory.
17. How do you set or change a user's GECOS field?
Answer: Use chfn username and follow prompts to change the GECOS fields, which include the full name, room number, work phone, and home phone.
18. How can you list all users with a specific shell?
Answer: Use grep "/path/to/shell" /etc/passwd to list users with a specific shell.
19. How do you remove a user from a group?
Answer: Use gpasswd -d username groupname or vigr to manually edit the group file and remove the user.
20. How can you change the default shell for new users?
Answer: Modify the DSHELL variable in /etc/default/useradd or use useradd -D -s /path/to/shell.
21. How do you copy a user's permissions to another user?
Answer: This is not straightforward, but you can manually set the new user's groups (usermod -G) to match the original user and ensure file permissions are set accordingly.
22. How can you disable login for all users except root?
Answer: One method is to change the shell for all users to /usr/sbin/nologin except for the root user.
23. How do you create a user without a home directory?
Answer: Use useradd -M username to create a user without a home directory.
24. How can you change the ownership of files owned by a deleted user?
Answer: Use find / -user oldUID -exec chown newUsername:newGroupname {} \; to change ownership of files owned by the deleted user's UID.
25. How do you set a user's account to expire on a specific date?
Answer: Use usermod -e YYYY-MM-DD username to set an expiration date for the user's account.
6. Manage Permissions
Question 1: How do you change file permissions using numerical mode?
Answer: Use the chmod command followed by the numerical mode, which represents the permissions, and the filename. For example, chmod 755 filename sets read, write, and execute permissions for the owner, and read and execute permissions for the group and others.
Question 2: Describe how to set the setuid bit on an executable file.
Answer: Use chmod u+s filename to set the setuid bit on an executable file. This allows the file to be executed with the file owner's permissions.
Question 3: How do you recursively change permissions for directories only?
Answer: Use find . -type d -exec chmod 755 {} + to change permissions to 755 on directories only, recursively.
Question 4: Explain the significance of the sticky bit for a directory.
Answer: The sticky bit (t) on a directory ensures that only the file owner, the directory owner, or the root user can delete or rename files within that directory. It's commonly used on shared directories like /tmp.
Question 5: How can you view the setuid, setgid, and sticky bit permissions on files in a directory?
Answer: Use ls -l to view permissions. Look for an s or t in the permission string. An s in the user execution spot indicates setuid, s in the group execution spot indicates setgid, and t indicates the sticky bit.
Question 6: How do you change the group ownership of a file?
Answer: Use chgrp groupname filename to change the group ownership of a file to groupname.
Question 7: Describe how to ensure new files in a directory inherit the directory's group ownership.
Answer: Use chmod g+s directoryname to set the setgid bit on a directory. This ensures new files inherit the directory's group ownership.
Question 8: How do you set default permissions for new files in a directory?
Answer: Use Access Control Lists (ACLs) with setfacl -d -m u::rwx,g::rwx,o::r directoryname to set default permissions for new files in a directory.
Question 9: How can you remove all permissions for the group and others on a file?
Answer: Use chmod go= filename to remove all permissions for the group and others.
Question 10: How do you give write permission to the group owner of a file, without affecting other permissions?
Answer: Use chmod g+w filename to add write permission for the group owner, without changing other permissions.
Question 11: Explain how to copy the permissions from one file to another without changing the ownership.
Answer: Use getfacl file1 | setfacl --set-file=- file2 to copy permissions from file1 to file2 without changing ownership.
Question 12: How do you remove a specific user's ACL from a file?
Answer: Use setfacl -x u:username filename to remove a specific user's ACL from a file.
Question 13: How can you recursively remove the execute permission for all users on all files within a directory?
Answer: Use find directoryname -type f -exec chmod a-x {} + to recursively remove execute permissions for all users on all files within a directory.
Question 14: Describe the process to change the owner and group of a file simultaneously.
Answer: Use chown ownername:groupname filename to change both the owner and group of a file simultaneously.
Question 15: How do you make a script executable by everyone but writable only by the owner?
Answer: Use chmod 755 script.sh to make the script executable by everyone but writable only by the owner.
7. Storage Management Essentials
Question 1: How do you list all disks and partitions in a Linux system?
Answer: Use the command lsblk to list all available disks and partitions. For more detailed information, including filesystem types, use fdisk -l with root privileges.
Question 2: Describe how to check the filesystem type of a disk partition in Linux.
Answer: Use the blkid command, for example, blkid /dev/sda1, to check the filesystem type of the partition /dev/sda1.
Question 3: How do you create a new partition on a disk?
Answer: Use a tool like fdisk or parted. For instance, sudo fdisk /dev/sda and follow the interactive menu to create a new partition.
Question 4: Explain how to format a partition with the ext4 filesystem.
Answer: Use the mkfs.ext4 command followed by the partition name, for example, mkfs.ext4 /dev/sda1, to format the partition /dev/sda1 with the ext4 filesystem.
Question 5: How can you mount a filesystem automatically at boot time?
Answer: Add an entry for the filesystem in the /etc/fstab file with the desired options to ensure it mounts automatically at boot time.
Question 6: Describe the process to resize an ext4 filesystem.
Answer: First, modify the partition size using a tool like parted or fdisk. Then, resize the filesystem with resize2fs /dev/sdXN, where /dev/sdXN is the partition.
Question 7: How do you check the disk space usage of a directory?
Answer: Use the du command. For example, du -sh /path/to/directory shows the total space used by the directory and its contents in human-readable form.
Question 8: How can you monitor the real-time disk I/O activity on your system?
Answer: Use the iotop or iostat command. iotop provides a real-time view similar to top, while iostat gives periodic reports.
Question 9: Explain how to create a swap file and enable it.
Answer: Use fallocate -l 1G /swapfile to create a 1GB swap file, secure it with chmod 600 /swapfile, create the swap with mkswap /swapfile, and activate it with swapon /swapfile. Add it to /etc/fstab for permanence.
Question 10: How do you repair a corrupt ext4 filesystem?
Answer: Use fsck.ext4 or e2fsck on the unmounted partition, for example, fsck.ext4 /dev/sda1. Ensure the filesystem is not mounted to prevent data corruption.
Question 11: Describe how to extend a logical volume using LVM.
Answer: First, ensure you have free space in the volume group (VG). Use lvextend to extend the logical volume (LV), then resize the filesystem with resize2fs for ext4, or the appropriate tool for your filesystem.
Question 12: How do you change the UUID of a filesystem?
Answer: Use tune2fs /dev/sdXN -U random to change the UUID of an ext2/3/4 filesystem. Replace /dev/sdXN with your partition.
Question 13: Explain how to set up a RAID 1 array on Linux.
Answer: Use mdadm to create a RAID 1 array. For example, mdadm --create /dev/md0 --level=1 --raid-devices=2 /dev/sda /dev/sdb creates a RAID 1 array with two disks.
Question 14: How can you find the UUID of a disk in Linux?
Answer: Use the blkid command, for example, blkid /dev/sda1, to display the UUID and other details of /dev/sda1.
Question 15: Describe the steps to manually mount an NFS share on a Linux system.
Answer: Use mount -t nfs server:/path/to/share /local/mountpoint to mount an NFS share located at server:/path/to/share to a local mount point.
9. Manage Networking
Question 1: How do you display all current network interfaces and their status on a Linux system?
Answer: Use the ip addr show command to list all network interfaces along with their IP addresses and status (up/down).
Question 2: Describe how to configure a static IP address on a network interface in Linux.
Answer: Edit the network configuration file for your interface, typically found in /etc/network/interfaces for Debian/Ubuntu or /etc/sysconfig/network-scripts/ifcfg-eth0 for CentOS/RHEL, and specify the static IP address, netmask, and gateway. Then, restart the network service or interface with systemctl restart networking or ifdown eth0 && ifup eth0.
Question 3: How can you check the routing table on a Linux system?
Answer: Use the ip route show or route -n command to display the kernel routing table.
Question 4: Explain how to add a default gateway in Linux.
Answer: Use the ip route add default via <gateway_ip> command, replacing <gateway_ip> with the IP address of the gateway.
Question 5: How do you change the DNS servers that a Linux system uses?
Answer: Edit the /etc/resolv.conf file to specify the DNS servers, using the nameserver keyword followed by the IP address of the DNS server. For systems using systemd-resolved, this configuration might be managed by systemd-networkd or NetworkManager.
Question 6: Describe how to open a specific port in the firewall on a Linux system using iptables.
Answer: Use the iptables -A INPUT -p tcp --dport <port_number> -j ACCEPT command to allow incoming connections on a specific port. Replace <port_number> with the port you wish to open.
Question 7: How can you list all current iptables rules?
Answer: Use the iptables -L command to list all current rules set in iptables.
Question 8: Explain how to restart the network service in Linux.
Answer: Depending on the distribution, use systemctl restart networking for systemd-based systems or service network restart for older systems.
Question 9: How do you enable IP forwarding in Linux?
Answer: Edit the /etc/sysctl.conf file to include the line net.ipv4.ip_forward=1, then apply the changes with sysctl -p.
Question 10: Describe how to assign multiple IP addresses to a single network interface in Linux.
Answer: Use the ip addr add <ip_address>/<mask> dev <interface> command for each additional IP address. Replace <ip_address>/<mask> with the IP address and subnet mask, and <interface> with the name of the network interface.
Question 11: How can you display the current TCP/IP network configuration for all interfaces?
Answer: Use the ip addr show command or the older ifconfig -a (if available) to display the IP configuration for all interfaces.
Question 12: Explain how to disable a network interface in Linux.
Answer: Use the ip link set dev <interface> down command, replacing <interface> with the name of the network interface you wish to disable.
Question 13: How do you release and renew an IP address using DHCP on a Linux system?
Answer: Use dhclient -r to release the current DHCP lease and dhclient to request a new lease.
Question 14: Describe the command to show the MAC address of a network interface in Linux.
Answer: Use the ip link show <interface> command, where <interface> is the name of the network interface. The MAC address is listed as the link/ether value.
Question 15: How can you test connectivity between your Linux system and another host?
Answer: Use the ping <hostname_or_IP> command to test connectivity to another host by sending ICMP echo requests.
10.Manage Software and SSH
Question 1: You need to install a package but don't know its exact name. How do you search for it?
Answer: Use the package manager's search functionality. For example, with apt on Debian/Ubuntu systems, you would use apt search package_name. On CentOS/RHEL systems with yum, you'd use yum search package_name.
Question 2: After updating a critical service via your package manager, it stops working. How do you troubleshoot and resolve this issue?
Answer: Start by checking the service's logs for error messages (e.g., using journalctl -u service_name or looking at /var/log/service_name). If the issue is due to the update, consider rolling back to a previous version of the package (e.g., apt-get install package_name=version or yum downgrade package_name), and check the project's documentation or forums for known issues with the new version.
Question 3: You're setting up a new server and need to ensure SSH access is secured. What steps do you take?
Answer:
- Change the default SSH port (Edit
/etc/ssh/sshd_config, setPortto a non-standard number). - Disable root login (
PermitRootLogin no). - Enable public key authentication (
PubkeyAuthentication yes) and disable password authentication (PasswordAuthentication no). - Consider setting up fail2ban to protect against brute force attacks.
- Limit SSH access to certain users with
AllowUsersorAllowGroups.
Question 4: A developer needs temporary access to your server via SSH. How do you provide access securely?
Answer: Create a new user account for the developer with useradd, set a strong password, and restrict the user's permissions to only what's necessary. Alternatively, if using public key authentication, ask for their public key and add it to the authorized_keys file of an existing or new user account with limited privileges. Ensure to remove the account or key after the access period ends.
Question 5: How do you automate the installation of security updates on your Linux server?
Answer: On Debian/Ubuntu, configure unattended-upgrades to automatically install security updates. On CentOS/RHEL, use yum-cron for automatic updates. Ensure to configure email notifications for updates to monitor what changes are applied.
Question 6: You need to SSH into a server, but your usual workstation is not available. How do you ensure the connection is secure from a different machine?
Answer: Use a trusted machine with a securely stored SSH key or portable SSH key stored on a secure USB drive. Verify the server's fingerprint upon first connection to ensure you're not subject to a man-in-the-middle attack. Avoid using public or shared computers where your credentials could be compromised.
Question 7: How can you roll back a software package to a previous version after an update causes issues?
Answer: Use the package manager to specify the desired version of the package. For apt, use apt-get install package=version. For yum, use yum downgrade package-version. Check the package manager's documentation for the exact syntax and options.
Question 8: What steps would you take if you're unable to connect to a server via SSH?
Answer:
- Verify network connectivity with
pingortraceroute. - Check the SSH service status on the server using a console or alternative access method.
- Confirm the firewall settings on both the client and server sides allow the SSH connection.
- Check the SSH configuration for any recent changes (
/etc/ssh/sshd_config). - Review SSH authentication logs for error messages (
/var/log/auth.logon Debian/Ubuntu or/var/log/secureon CentOS/RHEL).
Question 9: How do you manage software packages on a server without direct internet access?
Answer: Use an internal repository mirror that syncs with external sources or manually download packages and their dependencies to a machine with internet access, then transfer and install them on the server using the package manager's local installation option (e.g., dpkg -i package.deb or rpm -ivh package.rpm).
Question 10: A team member accidentally removed a critical software package, causing system instability. How do you recover?
Answer: Identify the removed package and its dependencies. Reinstall the package using the package manager (apt install package_name for Debian/Ubuntu or yum install package_name for CentOS/RHEL). Check system logs and testing to ensure system stability is restored. Consider implementing user privilege management to prevent future accidents.
11.Manage Time
Question 1: How do you synchronize the system time with an external NTP server?
Answer: Install and configure the ntpd or chronyd service. For ntpd, edit /etc/ntp.conf to add NTP server addresses, then restart the service with systemctl restart ntp. For chronyd, use /etc/chrony/chrony.conf for configuration, and restart with systemctl restart chronyd.
Question 2: A server is reporting the wrong time zone. How do you correct it?
Answer: Use timedatectl set-timezone <Timezone>, replacing <Timezone> with the correct time zone (e.g., America/New_York). Confirm by viewing the current time with date.
Question 3: How can you ensure the system clock remains accurate even when the server is offline?
Answer: Enable NTP synchronization with a hardware clock. Use hwclock --systohc to sync the system time to the hardware clock periodically or at shutdown. Ensure chronyd or ntpd is configured to correct the system clock at startup.
Question 4: Describe the process to update the hardware clock time to match the system clock.
Answer: Use the command hwclock --systohc. This updates the hardware clock (RTC) to match the system clock time. Run as root or with sudo privileges.
Question 5: How do you view the current system time, including the time zone?
Answer: Use the timedatectl command, which displays the local time, universal time, RTC time, time zone, and NTP synchronization status.
Question 6: A process needs to run when daylight saving time changes, but you want to avoid issues caused by the time change. How do you handle this?
Answer: Schedule the task for a time unaffected by daylight saving changes (e.g., early morning if DST ends at 2 am, schedule after 4 am). Alternatively, use UTC time for cron jobs to avoid DST adjustments entirely.
Question 7: How can you change the system clock manually without affecting the hardware clock?
Answer: Use date -s "YYYY-MM-DD HH:MM:SS" to set the system clock manually. This change does not affect the hardware clock until you explicitly sync with hwclock --systohc.
Question 8: Your system is part of a distributed application that requires precise timekeeping. How do you minimize time drift?
Answer: Configure NTP or Chrony for frequent synchronization with reliable NTP servers. For highly sensitive environments, consider using PTP (Precision Time Protocol) if supported by your network infrastructure.
Question 9: How do you configure a Linux system to act as an NTP server for your local network?
Answer: Install ntpd or chronyd. Configure the service to allow serving time to your local network by editing /etc/ntp.conf or /etc/chrony/chrony.conf, respectively, adding your local network to the allow directive. Restart the service and ensure your firewall allows NTP traffic (UDP port 123).
Question 10: After daylight saving time adjustment, a critical job ran an hour off schedule. How do you prevent this in the future?
Answer: Ensure the system uses a time zone that correctly observes daylight saving changes, and consider scheduling jobs in UTC to avoid DST issues. For cron jobs, verify the system's cron daemon handles DST correctly or adjust schedules to account for DST if needed.
Question 11: How do you check if your system is using NTP for time synchronization?
Answer: Run timedatectl. It shows whether NTP synchronization is active. For detailed NTP status, use ntpq -p for ntpd or chronyc sources for chronyd.
12.Work with Processes
Question 1: How do you view the currently running processes on a Linux system?
Answer: Use the ps aux command to display all running processes. For a dynamic, real-time view, use top or htop (which provides a more user-friendly interface).
Question 2: A web server process is unresponsive. How do you terminate it safely?
Answer: First, try to gracefully stop the process using kill -SIGTERM <pid> (where <pid> is the Process ID). If it remains unresponsive, use kill -SIGKILL <pid> to forcefully terminate it.
Question 3: You suspect a process is consuming more resources than it should. How do you check its resource usage?
Answer: Use top or htop to monitor resource usage in real-time. To see a specific process's resource usage, use ps aux | grep process_name or pidstat -p <pid> for detailed statistics.
Question 4: How can you increase the priority of a critical process?
Answer: Use the nice command to start a process with a defined niceness (priority) or renice to change the priority of an already running process. Remember, a lower nice value gives higher priority. Only root can increase priority (lower niceness).
Question 5: A process is not responding to a termination request. How do you force it to stop?
Answer: Use kill -9 <pid> or kill -SIGKILL <pid> to forcefully terminate the process. This signal cannot be caught or ignored by the process.
Question 6: How do you find out which process is listening on a specific port?
Answer: Use netstat -tulnp | grep :<port> or ss -tulnp | grep :<port> to find processes listening on a specific port. The -p option shows the process ID and name.
Question 7: How can you run a process in the background and ensure it continues running after you log out?
Answer: Start the process with nohup command & or use the disown command on an already running background process. screen or tmux can also be used for session management, allowing processes to continue running in a detachable session.
Question 8: You need to start a backup process that requires several hours to complete. How do you ensure it does not consume too many resources and affect server performance?
Answer: Use the nice command to start the backup process with a lower priority, e.g., nice -n 10 command, so it consumes fewer CPU resources. Use ionice for controlling disk I/O priority if the process is I/O intensive.
Question 9: A process supposed to run 24/7 crashed overnight. How do you ensure it automatically restarts after failure?
Answer: Use a process supervisor like systemd, supervisord, or runit to manage the process. These tools can monitor the process and automatically restart it upon failure. For systemd, create a service unit file with Restart=on-failure in the [Service] section.
Question 10: How do you isolate and manage a group of processes together?
Answer: Use cgroups (control groups) to group processes and manage their system resource allocation. cgroups allow you to allocate resources—such as CPU time, system memory, network bandwidth, or combinations of these resources—among user-defined groups of tasks (processes).
Question 11: How do you capture the output of a process for later analysis?
Answer: Redirect the output to a file using the > operator for stdout (e.g., command > output.txt) or 2> for stderr. Use command &> output.txt to capture both stdout and stderr. For running processes, use strace or tee with a pipe for real-time capturing.
Question 12: How can you run a command at a specific time without being present?
Answer: Use the at command to schedule the command execution for a specific time, e.g., echo "command" | at now + 1 hour. Ensure the atd daemon is running.
13.Schedule Tasks
Question 1: How do you create a cron job to run a script at 2 AM every day?
Answer: Edit the crontab for the desired user with crontab -e and add the following line: 0 2 * * * /path/to/script.sh. This schedules the script to run at 2 AM daily.
Question 2: A cron job is supposed to run every Sunday at 1 PM, but it's not executing. How do you troubleshoot this?
Answer:
- Check the cron syntax: Ensure the cron line is correctly formatted.
- Verify cron daemon status: Ensure
crondis running (systemctl status crondorcron). - Script permissions: Make sure the script is executable (
chmod +x script.sh). - Environment variables: Cron jobs run in a limited environment, so ensure your script does not rely on environment variables not set within the script or the crontab.
- Log files: Check
/var/log/cronfor entries related to your cron job.
Question 3: How can you list all cron jobs scheduled for the current user?
Answer: Use crontab -l to list all cron jobs for the current user.
Question 4: You need to run a script every 15 minutes. What cron expression do you use?
Answer: Add the following line to your crontab: */15 * * * * /path/to/script.sh. This schedules the script to run at every 15-minute interval.
Question 5: How do you prevent email notifications from a specific cron job?
Answer: Append >/dev/null 2>&1 to the end of the cron job line to redirect both stdout and stderr to null, preventing email alerts. Alternatively, set MAILTO="" at the beginning of the crontab to disable email alerts for all cron jobs.
Question 6: How do you schedule a one-time job to run at a specific time using at?
Answer: Use the at command followed by the time for the job to run, then enter the command to run and press Ctrl+D. For example, to run a script at 10:30 AM on July 4, you would use: at 10:30 AM Jul 4, then ./path/to/script.sh, followed by Ctrl+D.
Question 7: A scheduled backup job needs to run when the system load is low. How do you automate this?
Answer: Use the batch command instead of at or cron. The batch command runs tasks when the system load average drops below 1.5 or the value specified by atd.
Question 8: How can you edit the crontab for a user named john from another user account?
Answer: As root or a user with appropriate permissions, use crontab -u john -e to edit John's crontab.
Question 9: You want to schedule a script to run at reboot. How do you do this with cron?
Answer: Add an @reboot directive in the crontab with crontab -e followed by the script you want to run, like: @reboot /path/to/script.sh.
Question 10: How do you temporarily disable a cron job without deleting it?
Answer: Edit the user's crontab with crontab -e and comment out the cron job by adding # at the beginning of the line. This disables the job without permanently removing it.
Question 11: How can you ensure a scheduled task runs even if the server restarts unexpectedly?
Answer: For tasks that must run once or at a specific interval regardless of restarts, consider using @reboot in cron to ensure execution upon restart, or manage the task with a system service manager like systemd that can be configured to start tasks at boot and restart them automatically after failure.
Question 12: What's the difference between cron and anacron, and when would you use each?
Answer: cron is used for scheduling recurring tasks at fixed times, dates, or intervals. anacron is used for scheduling recurring tasks that should run regularly but not at a specific hour or minute, ideal for systems that may not be running 24/7. Use anacron for tasks that need to run daily, weekly, or monthly but don't require precise timing, ensuring they are executed at least as frequently as specified, regardless of system downtime.
14. Read Log Files
Question 1: How do you view the contents of a log file in real-time?
Answer: Use the tail -f /path/to/logfile command to view the log file in real-time. This command keeps the file open and prints new messages to the terminal as they are added to the file.
Question 2: A web server is returning 500 Internal Server Error responses. How would you investigate this?
Answer: Check the web server's error log file (e.g., /var/log/apache2/error.log for Apache or /var/log/nginx/error.log for Nginx). Use grep to filter for error messages related to the 500 status code, which can provide clues about the cause.
Question 3: You need to find all occurrences of a specific error message within a log file. How do you accomplish this?
Answer: Use the grep command to search for specific patterns in the log file. For example, grep "specific error message" /path/to/logfile displays all lines containing "specific error message".
Question 4: A system's disk space usage suddenly increases. How can you identify which log files are consuming the most space?
Answer: Use the du -h /var/log | sort -rh | head command to list the sizes of log files and directories under /var/log, sorted by size in human-readable format. This helps identify large files.
Question 5: How do you display the last 100 lines of a log file?
Answer: Use tail -n 100 /path/to/logfile to display the last 100 lines of the specified log file.
Question 6: A process crashes periodically, and you suspect a specific error is logged each time. How can you monitor the log for this error?
Answer: Use tail -f /path/to/logfile | grep "specific error" to monitor the log file in real-time, filtering for lines that contain "specific error".
Question 7: How would you extract log entries within a specific time range from a log file?
Answer: Use sed or awk to filter entries based on the time range. For example, to extract entries from 01:00 to 02:00 on July 15, 2023, you could use: awk '/15\/Jul\/2023:01/,/15\/Jul\/2023:02/' /path/to/logfile
Question 8: After a security breach, you need to audit all successful login attempts. Which log files should you check?
Answer: Check the /var/log/auth.log file on Debian/Ubuntu systems or /var/log/secure on RHEL/CentOS systems for entries related to successful authentication attempts.
Question 9: You suspect an application leak memory over time. Which tool can help you monitor its memory usage in its logs?
Answer: Use journalctl for systemd-managed services to monitor its logs, e.g., journalctl -u service_name.service. Combine with grep to filter for memory-related messages or use | less to manually scan through the log.
Question 10: How do you set up log rotation for a custom application log to prevent it from consuming too much disk space?
Answer: Configure logrotate for your application by creating a configuration file in /etc/logrotate.d/. Specify the path to your log file, and set options like rotate, compress, daily, size, etc., to control how often the log is rotated and how many old versions are kept.
Question 11: How can you correlate events logged in different files at the same time to diagnose a complex issue?
Answer: Use multitail to view multiple log files in a single window, allowing you to compare events in real time. For historical data, use grep with timestamps across different log files or custom scripts to extract and align log entries based on time.
Question 12: How do you automate the monitoring of log files for specific patterns and send alerts?
Answer: Use tools like logwatch, swatch, or fail2ban configured to scan log files for specific patterns and execute actions like sending email alerts or executing scripts in response to matches.
No comments:
Post a Comment