简体   繁体   English

如何创建一个 bash 脚本来检查 SSH 连接?

[英]How to create a bash script to check the SSH connection?

I am in the process of creating a bash script that would log into the remote machines and create private and public keys.我正在创建一个 bash 脚本,该脚本将登录到远程机器并创建私钥和公钥。

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.我需要一个 bash 脚本来检查 SSH 连接是否已启动。 Before actually creating the keys for future use.在实际创建密钥以供将来使用之前。

You can check this with the return-value ssh gives you:您可以使用 ssh 为您提供的返回值进行检查:

$ ssh -q user@downhost exit
$ echo $?
255

$ ssh -q user@uphost exit
$ echo $?
0

EDIT: Another approach would be to use nmap (you won't need to have keys or login-stuff):编辑:另一种方法是使用 nmap (你不需要有密钥或登录的东西):

$ 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)

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).但是您必须 grep 消息(nmap 不使用返回值来显示端口是否被过滤、关闭或打开)。

EDIT2:编辑2:

If you're interested in the actual state of the ssh-port, you can substitute grep open with egrep 'open|closed|filtered' :如果您对 ssh 端口的实际状态感兴趣,可以将grep open替换为egrep 'open|closed|filtered'

$ nmap host -PN -p ssh | egrep 'open|closed|filtered'

Just to be complete.只是为了完整。

You can use something like this你可以使用这样的东西

$(ssh -o BatchMode=yes -o ConnectTimeout=5 user@host echo ok 2>&1)

This will output "ok" if ssh connection is ok如果 ssh 连接正常,这将输出“ok”

ssh -q -o "BatchMode=yes" -i /home/sicmapp/.ssh/id_rsa <ID>@<Servername>.<domain> "echo 2>&1" && echo $host SSH_OK || echo $host SSH_NOK

Complementing the response of @Adrià Cidre you can do:补充@Adrià Cidre的回应,你可以这样做:

status=$(ssh -o BatchMode=yes -o ConnectTimeout=5 user@host echo ok 2>&1)

if [[ $status == ok ]] ; then
  echo auth ok, do something
elif [[ $status == "Permission denied"* ]] ; then
  echo no_auth
else
  echo other_error
fi

尝试:

echo quit | telnet IP 22 2>/dev/null | grep Connected

Below ssh command should have an exit code of 0 on a successful connection and a non-zero value otherwise.ssh命令下,成功连接时的退出代码应为0 ,否则为非零值。

ssh -q -o BatchMode=yes user@remote.com exit

if [ $? != "0" ]; then
    echo "Connection failed"
fi

Following @user156676, to check a range of ips:关注@user156676,检查ips范围:

#!/bin/sh
IP='192.168.0.'
PWD='your_password'
USR='your_usr'

for i in $(seq 229 255);do
    sshpass -p $PWD ssh -q -o ConnectTimeout=3 ${USR}@${IP}${i} exit
    let ret=$?
    if [ $ret -eq 5 ]; then
        echo $IP$i "Refused!"  $ret
    elif [ $ret -eq 255 ] ; then
        echo $IP$i "Server Down!" $ret
    elif [ $ret -eq 0 ] ; then
        echo $IP$i "Connnected!" $ret
    else
        echo $IP$i "Unknown return code!" $ret
    fi  
done

Just in case someone only wishes to check if port 22 is open on a remote machine, this simple netcat command is useful.万一有人只想检查远程机器上的端口 22 是否打开,这个简单的 netcat 命令很有用。 I used it because nmap and telnet were not available for me.我使用它是因为 nmap 和 telnet 对我不可用。 Moreover, my ssh configuration uses keyboard password auth.此外,我的 ssh 配置使用键盘密码身份验证。

It is a variant of the solution proposed by GUESSWHOz.它是 GUESSWHOz 提出的解决方案的变体。

nc -q 0 -w 1 "${remote_ip}" 22 < /dev/null &> /dev/null && echo "Port is reachable" || echo "Port is unreachable"

If you would like to check a remote folder exists, or any other file-test really:如果您想检查远程文件夹是否存在,或者任何其他文件测试真的:

if [ -n "$(ssh "${user}@${server}" [ -d "$folder" ] && echo 1; exit)" ]; then
    # exists
else
    # doesn't exist
fi

Do not forget the quotes in "$(ssh ...)" .不要忘记"$(ssh ...)"的引号。

连接到具有多个接口的服务器

ssh -o ConnectTimeout=1 -q Necktwi@192.168.1.61;[ $? = 1 ] || ssh -o ConnectTimeout=1 -q Necktwi@192.168.1.51

Example Using BASH 4+ script:使用 BASH 4+ 脚本的示例:

# -- ip/host and res which is result of nmap (note must have nmap installed)
ip="192.168.0.1"
res=$(nmap ${ip} -PN -p ssh | grep open)

# -- if result contains open, we can reach ssh else assume failure) --
if [[ "${res}" =~ "open" ]] ;then
    echo "It's Open! Let's SSH to it.."
else
    echo "The host ${ip} is not accessible!"
fi

https://onpyth.blogspot.com/2019/08/check-ping-connectivity-to-multiple-host.html https://onpyth.blogspot.com/2019/08/check-ping-connectivity-to-multiple-host.html

Above link is to create Python script for checking connectivity.上面的链接是创建用于检查连通性的 Python 脚本。 You can use similar method and use:您可以使用类似的方法并使用:

ping -w 1 -c 1 "IP Address" 

Command to create bash script.创建 bash 脚本的命令。

I wrote this script to check both netcat and SSH connectivity to all hosts in my servers /etc/hosts我写了这个脚本来检查 netcat 和 SSH 连接到我的服务器 /etc/hosts 中的所有主机

reads /etc/hosts line by line and then tries netcat port 22, and then ssh as "sshuttle" user逐行读取 /etc/hosts 然后尝试 netcat 端口 22,然后以“sshuttle”用户身份 ssh

quick way to check network sanity检查网络健全性的快速方法

script uses a "sshuttle" user, this is an account that has pub/priv keys on all my hosts and can ssh anywhere (non root account), we use this acct to spin up sshuttle VPN tunnels, but you can add any account that has SSH access to servers脚本使用“sshuttle”用户,这是一个在我的所有主机上都具有 pub/priv 密钥的帐户,并且可以在任何地方 ssh(非 root 帐户),我们使用此帐户来启动 sshuttle VPN 隧道,但您可以添加任何帐户可以通过 SSH 访问服务器

https://gist.github.com/perfecto25/8687d563716ba4923c77162be724beda https://gist.github.com/perfecto25/8687d563716ba4923c77162be724beda

output,输出,

./conncheck.sh


netcat is installed, proceeding..
--------------------------------------
tm-us1 (127.0.0.1): ssh OK | nc OK
--------------------------------------
localhost (127.0.0.1): ssh OK | nc OK
--------------------------------------
atlas (192.168.142.21): ssh ERROR | nc OK
--------------------------------------
hydra (192.168.142.22): ssh OK | nc OK
--------------------------------------
nemesis (192.168.140.23): ssh OK | nc OK
--------------------------------------
vulcan (192.168.140.24): ssh OK | nc OK
--------------------------------------
athena (192.168.140.27): ssh OK | nc OK
--------------------------------------
nas1 (192.168.100.101): ssh ERROR | nc OK
--------------------------------------
tm-dev (192.10.23.71): ssh ERROR | nc ERROR
--------------------------------------
WARNING: Your password has expired.
Password change required but no TTY available.
infra01 (192.10.23.186): ssh ERROR | nc OK
--------------------------------------
ns-us1 (192.10.23.252): ssh ERROR | nc OK
--------------------------------------
ns-us2 (192.10.23.182): ssh ERROR | nc OK
--------------------------------------
proxy-us1 (192.10.23.120): ssh OK | nc OK
--------------------------------------
simtm-us1 (192.10.23.236): ssh OK | nc OK
--------------------------------------
tm-us1 (192.10.23.104): ssh OK | nc OK
--------------------------------------
tm-us2 (192.10.23.215): ssh OK | nc OK
--------------------------------------
tm-dev (192.10.23.77): ssh OK | nc OK
--------------------------------------
WARNING: Your password has expired.
Password change required but no TTY available.
tm-uat (192.10.23.225): ssh ERROR | nc OK
--------------------------------------
vpn-us1 (192.10.23.193): ssh OK | nc OK
--------------------------------------

I feel like you're trying to solve the wrong problem here.我觉得你在这里试图解决错误的问题。 Shouldn't you be trying to make the ssh daemons more stable?您不应该尝试使 ssh 守护进程更稳定吗? Try running something like monit , which will check to see if the daemon is running and restart it if it isn't (giving you time to find the root problem behind sshd shutting down on you).尝试运行monit 之类的东西,它会检查守护进程是否正在运行,如果不是,则重新启动它(让您有时间找到 sshd 关闭背后的根本问题)。 Or is the network service troublesome?还是网络服务麻烦? Try looking at man ifup .试试看man ifup Does the Whole Damn Thing just like to shut down on you?整个该死的东西只是喜欢关闭你吗? Well, that's a bigger problem ... try looking at your logs (start with syslog) to find hardware failures or services that are shutting your boxen down (maybe a temperature monitor?).嗯,这是一个更大的问题......尝试查看您的日志(从系统日志开始)以查找正在关闭您的 boxen 的硬件故障或服务(也许是温度监视器?)。

Making your scripts fault tolerant is great, but you might also want to make your boxen fault tolerant.使您的脚本具有容错能力固然很好,但您可能还希望使您的 boxen 具有容错能力。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM