diff --git a/k3os-toggle-sshd-password-auth.sh b/k3os-toggle-sshd-password-auth.sh index 9401647..a9148e4 100644 --- a/k3os-toggle-sshd-password-auth.sh +++ b/k3os-toggle-sshd-password-auth.sh @@ -6,14 +6,12 @@ AUTH_LINE="PasswordAuthentication" # --- Function to check the current state --- get_current_state() { - # Search the file, handle lines commented out with #, and extract the effective value. - # The 'yq' tool (or similar) is ideal for YAML/JSON, but 'grep' is standard for config files. - # We use a pattern that handles optional whitespace and comments. + # Using -E for extended regular expressions instead of -P for broader compatibility - # 1. Use grep to find the line, ignoring comments that start the line + # 1. Use grep to find the line, including commented lines # 2. Use sed to remove leading/trailing whitespace and the setting name # 3. Use tr to convert to lowercase for reliable comparison - CURRENT_STATE=$(grep -iP "^\s*#?\s*${AUTH_LINE}\s+" "$SSH_CONFIG_FILE" | \ + CURRENT_STATE=$(grep -iE "^\s*#?\s*${AUTH_LINE}\s+" "$SSH_CONFIG_FILE" 2>/dev/null | \ sed -E "s/^\s*#?\s*${AUTH_LINE}\s*//" | \ tr '[:upper:]' '[:lower:]' | \ head -n 1) @@ -24,9 +22,8 @@ get_current_state() { elif [[ "$CURRENT_STATE" == "yes" ]]; then echo "yes" else - # Handle cases where the setting is missing, which usually defaults to 'no' - # but check for an explicit 'no' in the file. - if grep -qP "^\s*${AUTH_LINE}\s+no" "$SSH_CONFIG_FILE"; then + # Handle cases where the setting is missing or invalid. Check for an explicit 'no'. + if grep -qE "^\s*${AUTH_LINE}\s+no" "$SSH_CONFIG_FILE" 2>/dev/null; then echo "no" else echo "no" # Defaulting to the most secure setting if not explicitly 'yes' @@ -64,7 +61,7 @@ if [[ "$response" =~ ^([yY])$ ]]; then sudo sed -i.bak -E "s/^\s*#?\s*${AUTH_LINE}\s+(yes|no)/${AUTH_LINE} ${NEW_STATE}/" "$SSH_CONFIG_FILE" # 2. If the line was missing or not matched (a rare edge case), ensure it is added - if ! grep -qP "^\s*${AUTH_LINE}\s+${NEW_STATE}" "$SSH_CONFIG_FILE"; then + if ! grep -qE "^\s*${AUTH_LINE}\s+${NEW_STATE}" "$SSH_CONFIG_FILE" 2>/dev/null; then echo "${AUTH_LINE} ${NEW_STATE}" | sudo tee -a "$SSH_CONFIG_FILE" > /dev/null fi