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
Related videos on Youtube
Author by
user441706
Updated on September 17, 2022Comments
-
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 over 13 yearsDamn! You beat me to it.
-
user441706 over 13 yearsthanks, 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 over 13 yearsYou need to specify a port too. nc -z -w 2 192.168.0.123 22 works as expected.
-
amrx over 7 years+1 for the
z
into. whoever you scan still can get info of who did the scan only without providing theidentification string
-
valentin_nasta over 7 yearsNote that this option works only with the netcat-openbsd package, otherwise the option is not present:
nc: invalid option -- 'z'
-
Edward Torvalds over 5 yearswithout
-w
option nc will be stuck forever on Ubuntu -
Edward Torvalds over 5 yearsthis should be selected answer, without
-w
optionnc
will be stuck forever on Ubuntu -
Mr. Pundir about 5 yearsBool can be used like =>
nc -zw 2 examplehost.com 22 && { echo "You can call your backup function" ; } || { echo "SSH Unavailable" ; }
-
Harshal Zope about 4 yearscan we have a similar command from windows
-
christianlc over 3 yearsThis 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
orssh -o ConnectTimeout=1 blah
-
robbash about 3 yearsIn my case the
nc
cmd was still outputting, have to use&> /dev/null
to silence it.