fix clear known hosts command

This commit is contained in:
Silas 2023-07-27 21:53:21 -04:00
parent 0467e6b309
commit dc1f2e8823
Signed by: silentsilas
GPG Key ID: 4199EFB7DAA34349
1 changed files with 26 additions and 4 deletions

View File

@ -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}
;;
*)