Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I've changed my household router and broadband recently (to BT Infinity), and I've noticed that my SSH server has become fairly unreliable. Of course, I've set SSH to be forwarded to the correct host on the new router, and this must be true as I can sometimes connect to it remotely, but sometimes not.

I have a dedi and was hoping to make a script that would occasionally 'ping' the SSH server every now and then, to test if it was up. Is there a way to invoke the SSH command so that it just handshakes with the server and does no more, and returns a helpful status code to say the server is up or down? Just so that I can add it to a script like this:

#!/bin/bash

LOG_FILE="$HOME/ssh.log"

while [ true ]; do
    testSSH

    if [ $? -ne 0 ]; then
        echo "`date +%y%m%d-%H%M%S` server down" >> $LOG_FILE
    fi

    sleep 60
done

or, alternatively, would it be easy to make such a program?

EDIT: as an aside, if anyone's interested or is in the know on this, I've changed my port forwarding settings to user-defined IP address instead of by MAC address (the default), just incase, with the SSH host having a static IP. Not that I use MAC spoofing at all, but just because I've heard it's 'buggy' on the home hub. When I look at the connected devices page, I don't see my computer on there. There are switches between my computer and the router, but that shouldn't make any difference, right?

share|improve this question
add comment

1 Answer

up vote 3 down vote accepted
$ ssh -q host true

returns 0 if everything is fine and 255 if the connection timed out. This obviously only works if you can actually log in on that host.

If that is not an option, something like

$ echo "" | nc host port

gives me a "protocol mismatch" (and return value 0) if the connection to the server succeded and a return value of 1 if the connection was refused. You can also use the -w option to specify a custom timeout (again, return value of 1 if the connection times out).

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.