From dc1f2e88235cf1b2e557e54c9965f7cef63a9609 Mon Sep 17 00:00:00 2001 From: Silas Date: Thu, 27 Jul 2023 21:53:21 -0400 Subject: [PATCH] fix clear known hosts command --- dockdroid.sh | 30 ++++++++++++++++++++++++++---- 1 file changed, 26 insertions(+), 4 deletions(-) diff --git a/dockdroid.sh b/dockdroid.sh index a07cc33..75e45f3 100755 --- a/dockdroid.sh +++ b/dockdroid.sh @@ -99,15 +99,37 @@ case $1 in ;; clear-known-hosts) - echo "This will clear known hosts. Please run this command as root or use sudo." - - if [ "$EUID" -ne 0 ] + echo "This will clear known hosts." + + # EUID may not be available in all environments, instead you can use id -u to get the user ID + if [ "$(id -u)" -ne 0 ] then + echo "Please run as root or use sudo" exit 1 fi CONTAINER_IP=$(docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' ${CONTAINER_NAME}) - ssh-keygen -R ${CONTAINER_IP} + + # Define known_hosts and temporary file path + KNOWN_HOSTS_PATH="$HOME/.ssh/known_hosts" + TEMP_FILE="$HOME/.ssh/temp" + + # Check if the .ssh directory exists and is writable + if [ ! -d "$(dirname ${KNOWN_HOSTS_PATH})" ] || [ ! -w "$(dirname ${KNOWN_HOSTS_PATH})" ]; then + echo "The .ssh directory does not exist or is not writable" + exit 1 + fi + + # Check if the known_hosts file exists, if not, exit early as there's nothing to clear + if [ ! -f ${KNOWN_HOSTS_PATH} ]; then + echo "The known_hosts file does not exist. Nothing to clear." + exit 0 + fi + + # Create a temporary file and remove the line with CONTAINER_IP. If grep doesn't find a match, it will still create an empty file. + grep -v "${CONTAINER_IP}" ${KNOWN_HOSTS_PATH} > ${TEMP_FILE} || true + + mv ${TEMP_FILE} ${KNOWN_HOSTS_PATH} ;; *)