• VMware

    Learn about VMware virtualization for its products like vsphere ESX and ESXi, vCenter Server, VMware View, VMware P2V and many more

  • Linux

    Step by step configuration tutorials for many of the Linux services like DNS, DHCP, FTP, Samba4 etc including many tips and tricks in Red Hat Linux.

  • Database

    Learn installation and configuration of databases like Oracle, My SQL, Postgresql, etc including many other related tutorials in Linux.

  • How to test ssh connection using bash script in Linux

    There can be multiple scenarios due to which ssh connection may fail, some of them can be
    • network issues
    • password incorrect
    • passphrase incorrect
    • and many more..

    so we will try to rule out all the possible failed scenarios with some pre-checks before we do the actual task to make sure my ssh doesn't get hang

    Ping Test

    ping -q -W 5 -c 1 $_HOST >/dev/null 2>&1

    Here I am doing a ping test with a timeout for 5 seconds and will send one packet to the target host to make sure my network is proper between client and server.

    Check port connectivity

    You can use multiple tools to check the port based connectivity to make sure target port is available

    timeout 5 bash -c "</dev/tcp/$_HOST/${_PORT}"


    On distributions with netcat rpm
    # netcat -w 5 ${_HOST} ${_PORT}

    if [ $_RETCODE -ne "0" ];then
        echo "Port 22 not available"

    Test ssh connectivity

    Here we will try to do a quick ssh and validate the return code
    ssh -q -o BatchMode=yes  -o StrictHostKeyChecking=no -i /export/home/sufuser/.ssh/id_rsa $_HOST 'exit 0'
    if [ $_RCODE -ne 0 ]
        log_and_print_red "unable to ssh, host is not accessible"

    I hope the article was useful.

    How to test ssh connection using bash script in Linux How to test ssh connection using bash script in Linux Reviewed by admin on Sunday, July 22, 2018 Rating: 5

    No comments:

    Powered by Blogger.