Linux 如何检查 sshd 是否在远程机器上运行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11968971/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to check if sshd runs on a remote machine
提问by barp
ssh -q -o "BatchMode=yes" user@host "echo 2>&1" && echo "OK" || echo "NOK"
this method is suitable but it returns true
when the pub.key is copied to host.
I need to see if an ssh is connectiable between two devices without keys.
这种方法是合适的,但是true
当 pub.key 被复制到主机时它会返回。我需要查看 ssh 是否可以在没有密钥的情况下在两个设备之间连接。
Simply wants to check if the sshd is running remotely.
只是想检查 sshd 是否正在远程运行。
采纳答案by Shawn Chin
If you just want to check if you can connect to a host via ssh, you could simply check if port 22 is open. There are various ways to to this.
如果您只想检查是否可以通过 ssh 连接到主机,您可以简单地检查端口 22 是否打开。有多种方法可以做到这一点。
Using nmap(replace localhost with your target host):
使用nmap(用你的目标主机替换 localhost):
$ nmap -p22 localhost
Starting Nmap 5.21 ( http://nmap.org ) at 2012-08-15 13:18 BST
Nmap scan report for localhost (127.0.0.1)
Host is up (0.000044s latency).
PORT STATE SERVICE
22/tcp open ssh
Nmap done: 1 IP address (1 host up) scanned in 0.04 seconds
To use this in a script:
要在脚本中使用它:
if nmap -p22 localhost -oG - | grep -q 22/open; then
echo "OK"
else
echo "NOK"
fi
You can also use netcat:
您还可以使用netcat:
$ nc -zv localhost 22
Connection to localhost 22 port [tcp/ssh] succeeded!
To use this in a script:
要在脚本中使用它:
if nc -zv localhost 80 2>&1 | grep -q succeeded; then
echo "OK"
else
echo "NOK"
fi
This is a quick check which is sufficient in most situations, however it is not fool-proof. There is no guarantee that the service listening on the remote port is actually an SSH server.
这是一个快速检查,在大多数情况下就足够了,但它不是万无一失的。无法保证在远程端口上侦听的服务实际上是 SSH 服务器。
You could attempt a dummy connection and inspect the returned header, e.g:
您可以尝试虚拟连接并检查返回的标头,例如:
$ echo "dummy" | nc localhost 22
SSH-2.0-OpenSSH_5.9p1 Debian-5ubuntu1
Protocol mismatch.
however such an approach is undesirable for various reasons. The only guaranteed way would be to establish an actual connection as you've shown in your question.
然而,由于各种原因,这种方法是不可取的。唯一有保证的方法是建立实际连接,如您在问题中所示。