如何创建一个bash脚本来检查SSH连接? [英] How to create a bash script to check the SSH connection?
问题描述
我在创建一个bash脚本,将登录到远程计算机,并创建私钥和公钥的过程。
I am in the process of creating a bash script that would log into the remote machines and create private and public keys.
我的问题是远程机器不是非常可靠,并且它们并不总是向上。我需要一个bash脚本,如果SSH连接到了那会检查。之前以备将来使用实际创建的键。
My problem is that the remote machines are not very reliable, and they are not always up. I need a bash script that would check if the SSH connection is up. Before actually creating the keys for future use.
推荐答案
您可以用返回值SSH检查,这给你:
You can check this with the return-value ssh gives you:
$ ssh -q user@downhost exit
$ echo $?
255
$ ssh -q user@uphost exit
$ echo $?
0
编辑:另一种方法是使用NMAP(你不需要有键或登录-东西):
Another approach would be to use nmap (you won't need to have keys or login-stuff):
$ a=`nmap uphost -PN -p ssh | grep open`
$ b=`nmap downhost -PN -p ssh | grep open`
$ echo $a
22/tcp open ssh
$ echo $b
(empty string)
但你必须到grep消息(NMAP不使用返回值显示,如果一个端口过滤,关闭或打开)。
But you'll have to grep the message (nmap does not use the return-value to show if a port was filtered, closed or open).
EDIT2:
如果你有兴趣在ssh端口的实际状态,可以替代的grep打开
与 egrep的'开|关|过滤
:
If you're interested in the actual state of the ssh-port, you can substitute grep open
with egrep 'open|closed|filtered'
:
$ nmap host -PN -p ssh | egrep 'open|closed|filtered'
只是要完成了。
这篇关于如何创建一个bash脚本来检查SSH连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!