• 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

    _HOST=192.168.100.10
    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
    ${_PORT}=22
    ${_HOST}=192.168.100.10

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

    OR





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

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

    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'
    _RCODE=$?
    if [ $_RCODE -ne 0 ]
    then
        log_and_print_red "unable to ssh, host is not accessible"
        continue
    fi

    I hope the article was useful.

    Deepak Prasad

    is a techie and an author who is still trying to survive in this IT generation with very little knowledge he has on Linux/Unix, VMware, SAN Storage, Automation, networking etc

    You can follow him on Facebook or Google+


    Do you also have something to share here?
    Join GoLinuxHub Team as an Author, Click here for more information
    How to test ssh connection using bash script in Linux How to test ssh connection using bash script in Linux Reviewed by Deepak Prasad on Sunday, July 22, 2018 Rating: 5

    No comments:

    Powered by Blogger.