How to do SSH Ping Test for Server Connectivity

A Guide for System Administrators:

Introduction:

In Unix/Linux system admin, daily BAU health checks often include verifying server login access. This method facilitates checking the connectivity status of a remote host using a standard SSH connection. It simply prints a message indicating whether the destination host is 'reachable' or 'unreachable' based on the success of the SSH login.

Key Features of sshping:

SSH Ping Test: 

It's straightforward. Log into a remote host via SSH, with or without a password. This test will confirm if the host is connected. You'll get 'reachable' if the login is successful, and 'unreachable' if it fails.

Connection Check Without Python: 

This method uses standard SSH to see if a remote host is connected. No Python or similar tools needed. It simply reports 'reachable' or 'unreachable' after the login attempt.

Server Reachability: 

In the tech world, it's common to check server accessibility without additional tools. By using the correct login credentials, you can quickly determine if a server is 'reachable' or 'not reachable'.

Below, I've provided a bash script featuring three distinct methods for logging into remote hosts, each method designed to meet specific requirements:

SSH Option 1: Password-Free SSH with Root:

SSH Option 2: Key-Based Password-Free SSH

SSH Option 3: SSH with Hidden and Safe Password

Setting Up sshping for Server Connectivity:

Step 1: User Configuration:

Begin by setting the DEFAULT_USER variable in the script. If you are using a non-root user for SSH access, replace DEFAULT_USER with your username. If you're using the root user, no changes are required.

# Default SSH user

DEFAULT_USER="root"


(to)


# Default SSH user

DEFAULT_USER="user_name"

Step 2: Script Installation:

To install sshping, copy the provided source code into a new file named /usr/bin/sshping on your Linux Jump/Bastion Host. 

This host should be configured to access your remote hosts using SSH authentication.

Source code for the sshping bash script. click hear to Download the script

#!/bin/bash

#Author: www.virtualnetworkingconcept.com

# ANSI escape codes for text colors

GREEN="\033[32m"

YELLOW="\033[33m"

RESET="\033[0m"


# Default SSH user

DEFAULT_USER="root"


# Parse arguments

if [[ "$1" == "-f" ]]; then

    if [[ -z "$2" || ! -f "$2" ]]; then

        echo "Error: No input file provided or file $2 not found!"

        exit 1

    fi

    # Read hosts from the file into an array

   mapfile -t hosts < <(sed 's/ //g' "$2" | grep '.'| sort -fu)

elif [[ -n "$1" ]]; then

    # Single hostname provided, store in array

    hosts=("$1")

else

    echo "Usage of SSH ping Test:"

    echo "  sshping <hostname>         - Test single host SSH connection"

    echo "  sshping -f <hosts-file>    - Test multiple Hosts SSH connections from a file"

    exit 1

fi


# Maximum number of parallel connections at a time (forking)

MAX_PARALLEL=100

count=0


# Start SSH connections

for host in "${hosts[@]}"; do

#------------------------------------#


#SSH Option-1: Passwordless SSH with root#

    ssh -q -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o BatchMode=yes -o ConnectTimeout=2 -o ServerAliveInterval=60 -o #ServerAliveCountMax=3 -o TCPKeepAlive=yes -o LogLevel=ERROR ${DEFAULT_USER}@$host exit > /dev/null && echo -e "$host ${GREEN}Reachable${RESET}" || echo -e "$host ${YELLOW}Unreachable${RESET}" &


#------------------------------------#

#SSH Option-2: Key-Based Passwordless SSH #

        #ssh -q -i /root/.ssh/id_rsa -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o BatchMode=yes -o ConnectTimeout=2 -o ServerAliveInterval=60 -o ServerAliveCountMax=3 -o TCPKeepAlive=yes -o LogLevel=ERROR ${DEFAULT_USER}@$host exit > /dev/null && echo "$host ${GREEN}Reachable${RESET}" || echo "$host ${YELLOW}NotReachable{RESET}" &


#------------------------------------#

#SSH option-3: Embedded Encrypted Password SSH Connection#

       #echo -n 'YOUR_SSH_PASSWORD' | openssl enc -aes-256-cbc -a -salt -pass pass:YOUR_PASSPHRASE 

       #execute above step for first time only to create encrypted password


       #encrypted_password='[PASTE ENCRYPTED STRING HERE]'

       #decrypted_password=$(echo "$encrypted_password" | openssl enc -aes-256-cbc -d -a -salt -pass pass:YOUR_PASSPHRASE)


    #sshpass -p "$decrypted_password" ssh -q -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o ConnectTimeout=2 -o ServerAliveInterval=60 -o ServerAliveCountMax=3 -o TCPKeepAlive=yes -o LogLevel=ERROR ${DEFAULT_USER}@$host exit > /dev/null && echo -e "$host  ${GREEN}Reachable${RESET}" || echo -e "$host ${YELLOW}Unreachable${RESET}" &

#------------------------------------#

        count=$((count + 1))

    # Wait for current batch to finish before starting new connections


    if [[ $count -ge $MAX_PARALLEL ]]; then

        wait

        count=0

    fi

done


# Wait for any remaining connections to complete

wait

Step 3: Setting Permissions:

After saving the script, change its permissions to ensure security and proper functioning. Execute the following commands:

Change the permission: chmod 700 /usr/bin/sshping

Set the owner (change root:root to your username and group if different): chown root:root /usr/bin/sshping

Note: 

In my case, this involves setting up SSH authentication for the root user.

So You should modify the ownership command (chown) to match your specific user and group needs. Additionally, avoid setting permissions that allow world access.

Script Features and Operations:

The sshping script supports various operations for efficient remote host login access test using SSH connection.

Note:

In my case, I have selected Option 1, which is 'Passwordless SSH with root'. Accordingly, I have uncommented (removed the #) the relevant lines in the script. You can similarly enable the options that best fit your requirements.

SSH Option-1: Passwordless SSH with root

Ensure that you have enabled passwordless SSH authentication with the root account for remote hosts if you're using Option 1.

SSH Option-2: Key-Based Passwordless SSH

Before proceeding with Option 2, ensure that key-based passwordless SSH authentication is set up for remote hosts. 

Additionally, remember to replace the highlighted yellow key location in the script code. /root/.ssh/id_rsa

SSH option-3: Embedded Encrypted Password SSH Connection

If you're going with Option 3, where we use an encrypted password, make sure you've created this password with OpenSSL using a passphrase. And remember, you need to replace the encrypted password in the script in the section that looks like this.

echo -n 'YOUR_SSH_PASSWORD' | openssl enc -aes-256-cbc -a -salt -pass pass:YOUR_PASSPHRASE

encrypted_password='[PASTE ENCRYPTED STRING HERE]'

Example:

In my case, I'm using the username 'root,' my password is 'linux123,' and my passphrase is 'linux.' After executing the command 

[root@server centos]# echo -n 'linux123' | openssl enc -aes-256-cbc -a -salt -pass pass:linux

U2FsdGVkX18WF9QPl+V67sra7GmawAdwLBn3q8sEo+E=

I obtained my encrypted password, which is: 

U2FsdGVkX18WF9QPl+V67sra7GmawAdwLBn3q8sEo+E=

Make sure to hardcode this encrypted password in the script's Section 3 like this: 

encrypted_password='U2FsdGVkX18WF9QPl+V67sra7GmawAdwLBn3q8sEo+E='

Additionally, when decrypting the password, don't forget to provide the passphrase in the salt option, like so:

decrypted_password=$(echo "$encrypted_password" | openssl enc -aes-256-cbc -d -a -salt -pass pass:linux)

The expected code for Option-3 should look like the following:

# SSH option-3 Embedded Encrypted Password SSH Connection#


#Define encrypted password

encrypted_password='U2FsdGVkX18WF9QPl+V67sra7GmawAdwLBn3q8sEo+E='


#Decrypt the password

decrypted_password=$(echo "$encrypted_password" | openssl enc -aes-256-cbc -d -a -salt -pass pass:linux)


sshpass -p "$decrypted_password" ssh -q -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o ConnectTimeout=2 -o ServerAliveInterval=60 -o ServerAliveCountMax=3 -o TCPKeepAlive=yes -o LogLevel=ERROR ${DEFAULT_USER}@$host exit > /dev/null && echo -e "$host  ${GREEN}Reachable${RESET}" || echo -e "$host ${YELLOW}Unreachable${RESET}" &

Important Note for: OpenSSL Version and Password Encryption Cipher

I'm using OpenSSL version 1.0.2k-fips on CentOS 7.9.2009. I've chosen the -aes-256-cbc encryption cipher for password security. 

This choice ensures compatibility and security according to my needs. You can change the encryption cipher to match your requirements.

To use SSH ping test, follow these steps:

After configuring the script, open your Linux terminal and type 'sshping,' then press Enter to access the help messages."

To test the SSH connection for a single host, use the command: sshping <hostname>

To test SSH connections for multiple hosts from a file, use the command: sshping -f <hosts-file>

[root@server centos]# sshping

Usage of SSH ping Test:

  sshping <hostname>         - Test single host SSH connection

  sshping -f <hosts-file>    - Test multiple Hosts SSH connections from a file

Crucial Security Note: 

If you're using 'SSH option-3: Embedded Encrypted Password SSH Connection,' 

it's essential to convert it into a binary executable file located at '/usr/bin/sshping.' Always prioritize security and avoid compromising it. 

Step 1: Install the necessary software packages by running the command: 

# yum install shc gcc

(Note: These packages are available in the EPEL repository.) 

Before you turn the script into a binary file, be sure to create a backup of the original source code at /usr/bin/sshping. This backup will be useful for any future needs. 

Step 2: Convert the script into a binary file using the following command: 

shc -f /usr/bin/sshping -o /usr/bin/sshping_binary

Next, replace the script file with the binary file by executing: 

mv /usr/bin/sshping_binary /usr/bin/sshping

After saving the binary file, change its permissions to ensure security and proper functioning. Execute the following commands:

Change the permission: chmod 700 /usr/bin/sshping

Set the owner (change root:root to your username and group if different): chown root:root /usr/bin/sshping

Note: In my case, this involves setting up SSH authentication for the root user. So You should modify the ownership command (chown) to match your specific user and group needs. Additionally, avoid setting permissions that allow world access.


Perform SSH Ping Test: 

You can now perform the SSH ping test using the binary file:

To test the SSH connection for a single host, use the command: sshping <hostname>

To test SSH connections for multiple hosts from a file, use the command: sshping -f <hosts-file>

Note: When adding remote hosts or IP addresses to the inventory file, remember to eliminate any empty spaces or lines.

These simple commands allow you to conduct SSH ping tests efficiently.

Conclusion:

The SSH ping test script is a flexible tool for checking remote host connectivity via SSH. It offers various login options and can be converted into a secure binary executable. Always prioritize security when using this tool to ensure effective server connectivity testing.