如何创建一个 bash 脚本来检查 SSH 连接? [英] How to create a bash script to check the SSH connection?

查看:19
本文介绍了如何创建一个 bash 脚本来检查 SSH 连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个 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).

编辑 2:

如果您对 ssh 端口的实际状态感兴趣,可以将 grep open 替换为 egrep 'open|closed|filtered':

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆