How can I check that a remote computer is online for ssh / script access?

49,278

Solution 1

Like this:

nc -z hostname 22 > /dev/null
echo $?

If it's 0 then it's available. If it's 1 then it's not.

Solution 2

Use netcat:

nc -z localhost 22

From the manpage

 -z      Specifies that nc should just scan for listening daemons,
         without sending any data to them.

Solution 3

Alternate:

nc -vzw 1 hostname 22
Share:
49,278

Related videos on Youtube

user441706
Author by

user441706

Updated on September 17, 2022

Comments

  • user441706
    user441706 over 1 year

    I'm writing a script that will backup data from my laptop to an Ubuntu server. To do so, I'm looking for a (ba)sh command to test if the server is available before starting the backup. something like ping on port 22 that returns a boolean.

    How can I do this?

  • bahamat
    bahamat over 13 years
    Damn! You beat me to it.
  • user441706
    user441706 over 13 years
    thanks, didn't know nc , i was wondering why nc -z -w 2 192.168.0.123 ( -w is the timeout option, in seconds ) does not timeout :|
  • chris
    chris over 13 years
    You need to specify a port too. nc -z -w 2 192.168.0.123 22 works as expected.
  • amrx
    amrx over 7 years
    +1 for the z into. whoever you scan still can get info of who did the scan only without providing the identification string
  • valentin_nasta
    valentin_nasta over 7 years
    Note that this option works only with the netcat-openbsd package, otherwise the option is not present: nc: invalid option -- 'z'
  • Edward Torvalds
    Edward Torvalds over 5 years
    without -w option nc will be stuck forever on Ubuntu
  • Edward Torvalds
    Edward Torvalds over 5 years
    this should be selected answer, without -w option nc will be stuck forever on Ubuntu
  • Mr. Pundir
    Mr. Pundir about 5 years
    Bool can be used like => nc -zw 2 examplehost.com 22 && { echo "You can call your backup function" ; } || { echo "SSH Unavailable" ; }
  • Harshal Zope
    Harshal Zope about 4 years
    can we have a similar command from windows
  • christianlc
    christianlc over 3 years
    This tests if port $host:22 is open, not if a sshd is taking requests, which means a false positive on any/all proxied requests. Just timeout ssh if you want a valid/reliable check timeout1 ssh blah or ssh -o ConnectTimeout=1 blah
  • robbash
    robbash about 3 years
    In my case the nc cmd was still outputting, have to use &> /dev/null to silence it.