The Act as approach asks a chatbot to adopt a specific expert role, such as a senior Linux system administrator. A detailed workplace task and operating context help shape a useful response. section 9.3
Automating kernel checks
Prompt: “Act as a senior Linux system administrator, adept in bash programming. Help write a script that reads servers from a file, checks each remote kernel with uname -r, compares it with an expected version, and records whether it is lower, equal, or higher.” The resulting script uses SSH, a comparison function, and an output file. section 9.3
#!/bin/bash
# Define the file containing the list of servers
SERVER_LIST='servers.txt'
# Expected kernel version
EXPECTED_KERNEL_VERSION='4.18.0-513.5.1.el8_9'
# Output file where results will be stored
OUTPUT_FILE='kernel_check_results.txt'
# Function to compare kernel versions
# Returns 0 if equal, 1 if first is higher, 2 if second is higher
compare_kernel_versions() {
# Using sort with version sort and tail to get the highest version
higher_version=$(echo -e "$1\n$2" | sort -V | tail -1)
if [ "$higher_version" == "$1" ] && [ "$higher_version" != "$2" ];
then
return 1 # First is higher
elif [ "$higher_version" != "$1" ] && [ "$higher_version" == "$2" ];
then
return 2 # Second is higher
else
return 0 # Versions are equal
fi
}
# Check if the SERVER_LIST file exists
if [ ! -f "$SERVER_LIST" ]; then
echo "Server list file $SERVER_LIST not found."
exit 1
fi
# Empty or create the output file
> "$OUTPUT_FILE"
# Read each line in SERVER_LIST as a server address
while IFS= read -r server; do
echo "Processing $server..."
# Get the kernel version of the server
server_kernel_version=$(ssh -o BatchMode=yes -o ConnectTimeout=5
"$server" 'uname -r')
# Compare the server's kernel version with the expected version
compare_kernel_versions "$server_kernel_version"
"$EXPECTED_KERNEL_VERSION"
comparison_result=$?
# Append comparison result to the output file
case $comparison_result in
0) echo "$server: Kernel version is equal to the expected (
$EXPECTED_KERNEL_VERSION)." >> "$OUTPUT_FILE";;
1) echo "$server: Kernel version is higher than expected (
$server_kernel_version > $EXPECTED_KERNEL_VERSION)." >>
"$OUTPUT_FILE";;
2) echo "$server: Kernel version is lower than expected (
$server_kernel_version < $EXPECTED_KERNEL_VERSION)." >>
"$OUTPUT_FILE";;
esac
done < "$SERVER_LIST"
echo "Script execution completed. Check $OUTPUT_FILE for results."
Review a complete Bash listing that reads server addresses, retrieves kernel versions, compares results, and writes a report. section 9.3
