Skip to content

Instantly share code, notes, and snippets.

@perfecto25
Last active July 2, 2023 09:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save perfecto25/8687d563716ba4923c77162be724beda to your computer and use it in GitHub Desktop.
Save perfecto25/8687d563716ba4923c77162be724beda to your computer and use it in GitHub Desktop.
checks netcat and ssh connectivity to all hosts in /etc/hosts file, outputs Errors
#!/bin/bash
# Run as root
# /home/sshuttle/conncheck.sh
## replace 'sshuttle' user with any user that has global SSH access to servers
file=${1:-"/etc/hosts"}
ncat_port=22
RED='\033[1;31m'
GREEN='\033[1;32m'
NC='\033[0m' # no color
bold=$(tput bold)
clear=$(tput sgr0)
## check if netcat is installed
if (type nc 2>&1 >/dev/null)
then
echo "netcat is installed, proceeding.."
else
echo -e "${RED}[ERROR]${NC} netcat is not installed on this host"
exit 1
fi
while read -r line
do
if [[ -n $line ]] && [[ "${line}" != \#* ]]
then
ip=$(echo $line | awk '{print $1}')
hostname=$(echo $line | awk '{print $2}')
## if ipv4
if [[ $ip =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
echo "--------------------------------------"
## check netcat connectivity
if (nc -z -w 2 $ip $ncat_port 2>&1 >/dev/null)
then
ncat_status="nc OK"
else
echo "${hostname} (${ip}): ${bold}nc ERROR${clear}"
continue
fi
## attempt ssh connection, get exit code
ssh -o ConnectTimeout=3 \
-o "StrictHostKeyChecking no" \
-o BatchMode=yes \
-i /home/sshuttle/.ssh/id_ed25519 \
-q sshuttle@"${ip}" exit </dev/null
if [ $? -eq 0 ]
then
ssh_status="ssh OK"
else
ssh_status="${bold}ssh ERROR${clear}"
fi
echo "${hostname} (${ip}): ${ncat_status} | ${ssh_status}"
fi
fi
done < "${file}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment