How to test SSH with Bash

How to test SSH with Bash

In this article, we will explore how to create a Bash script to test SSH connection to a remote host.

Bash scripting is a powerful resource for automating routine tasks and streamlining processes. In this article, we will explore how to create a Bash script to test SSH connection to a remote host. This type of script can be useful for checking connectivity before performing other operations or automations on a remote system.

Before getting started, ensure that the ssh package is installed on the system where you intend to run the script. To install it on Debian/Ubuntu-based systems, you can use the following command:


sudo apt-get install openssh-client

On Red Hat/Fedora-based systems, you can use the following command:


# Alternatively, using dnf
sudo yum install openssh-clients

Open a text editor and start writing our Bash script. In this example, we will use nano as the editor:


nano test_ssh_connection.sh

Now, insert the following code into the script:


#!/bin/bash

# Check if enough arguments are provided
if [ $# -ne 2 ]; then
    echo "Usage: $0  "
    exit 1
fi

# Assign parameters to variables
host=$1
user=$2

# Attempt to connect to the remote host
ssh -q -o BatchMode=yes -o ConnectTimeout=5 "${user}@${host}" 'echo' &>/dev/null

# Check the exit status of the ssh command
if [ $? -eq 0 ]; then
    echo "SSH connection successful to ${host} as ${user}"
else
    echo "SSH connection failed to ${host} as ${user}"
fi

This script takes two arguments: the hostname of the remote system and the username you want to connect with. It uses the ssh command to attempt a connection without requiring user input. Subsequently, it checks the exit status of the command to determine if the connection succeeded or failed.

Before running the script, make it executable with the following command:


chmod +x test_ssh_connection.sh

Now, you can execute the script by providing the hostname and username as arguments:


./test_ssh_connection.sh 192.168.1.7 username

The script will return a message indicating whether the SSH connection succeeded or failed.

This basic script can be further customized to meet specific needs, such as managing multiple hosts or logging results. Modifying and adapting the script to suit your requirements is an important step in fully harnessing the potential of Bash scripting.