bash 用于检查服务器是否可访问的 Shell 脚本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8937663/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 21:31:50  来源:igfitidea点击:

Shell script to check whether a server is reachable?

bashshellsolaris-10

提问by Balaswamy Vaddeman

I have 5 Solaris servers present across different locations. Sometimes some of these servers are not reachable from my location due to various reasons (either because of network problems or the server itself goes down suddenly).

我在不同的位置有 5 台 Solaris 服务器。有时,由于各种原因(由于网络问题或服务器本身突然停机),其中一些服务器无法从我的位置访问。

So I would like to write a Bash shell script to check wether they are reachable. What I have tried is:

所以我想写一个 Bash shell 脚本来检查它们是否可以访问。我尝试过的是:

ssh ipaddress "uname -a"

Password less authentication is set. If I don't get any any output I will generate a mail.

设置了无密码认证。如果我没有得到任何输出,我将生成一封邮件。

  1. Are there any otherways to check server reachability?
  2. Which one is the best way?
  3. Is what I have tried correct?
  1. 有没有其他方法可以检查服务器可达性?
  2. 哪一种是最好的方法?
  3. 我试过的正确吗?

采纳答案by jaypal singh

You can use ping -c4 $ip_addresswhere $ip_addressis the ip of your remote server and parse the output to capture the successful packets and/or failed packets and use mail -sto send the log via email.

您可以使用ping -c4 $ip_address这里$ip_address是你的远程服务器的IP地址和解析输出捕获的数据包成功和/或失败的分组,并使用mail -s通过电子邮件发送日志。

Here is something to get you started and you can build on it.

这里有一些东西可以帮助您入门,您可以在此基础上进行构建。

ping -c4 www.google.com | awk '/---/,0'

This will give an output like this -

这将给出这样的输出 -

[jaypal:~/Temp] ping -c4 www.google.com | awk '/---/,0'
--- www.l.google.com ping statistics ---
4 packets transmitted, 4 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 36.638/36.870/37.159/0.196 ms


I checked the Solaris man-pagefor ping. Output from pingon Solaris box is different. Also, on Linux you limit the packets by stating -cand number of packets. On Solaris you would have to do -

我检查了 Solarisman-pageping. pingSolaris 机器上的输出是不同的。此外,在 Linux 上,您可以通过说明-c和数据包数量来限制数据包。在 Solaris 上,您必须这样做 -

ping -s www.google.com 2 4

/usr/sbin/ping -s [-l | -U] [-adlLnrRv] [-A addr_family]
[-c traffic_class] [-g gateway [ -g gateway...]] [-
F flow_label] [-I interval] [-i interface] [-P tos] [-
p port] [-t ttl] host [data_size] [npackets]
                           ^           ^
                           |           |
---------------------------------------  

Unfortunately I don't have a solaris box handy to help you out with.

不幸的是,我没有方便的solaris 框来帮助您解决问题。

回答by flying sheep

The most barebones check you can do is probably to use netcatto check for open ports.

您可以做的最准系统检查可能是netcat用来检查开放端口。

to check for SSH (port 22) reachability, you can do

要检查 SSH(端口 22)可访问性,您可以执行以下操作

if nc -z $server 22 2>/dev/null; then
    echo "$server ?"
else
    echo "$server ?"
fi

from the manpage:

从联机帮助页:

-z  Specifies that nc should just scan for listening daemons, without sending any data to them.

-z  指定 nc 应该只扫描监听守护进程,而不向它们发送任何数据。

回答by gcbenison

Your ssh command will test for more than if the server is reachable - for it to work, the ssh server must be running, and everything must be right with authentication.

您的 ssh 命令将测试的不仅仅是服务器是否可访问 - 要使其工作,ssh 服务器必须正在运行,并且一切都必须通过身份验证。

To just see if the servers are up, how about just a simple ping?

要查看服务器是否已启动,仅进行简单的 ping 怎么样?

ping -c1 -W1 $ip_addr && echo 'server is up' || echo 'server is down'

回答by Katie

You could use these options from the ping man page:

您可以使用 ping 手册页中的这些选项:

  • only send one packet ("c1"),
  • quiet mode ("q"),
  • (optional) Wait for 1 second for a response ("W1")

    ping -c1 -W1 -q $server

  • 只发送一个数据包(“c1”),
  • 安静模式(“q”),
  • (可选)等待 1 秒以获取响应(“W1”)

    ping -c1 -W1 -q $server

Ping returns different exit codes depending on the type of error. So, to test if it worked or not, just do "echo $?" to get the exit code. Like this:

Ping 根据错误类型返回不同的退出代码。因此,要测试它是否有效,只需执行“echo $?” 获取退出代码。像这样:

ping 256.256.256.256 ; echo $?
# 68

ping -c 1 127.0.0.1 ; echo $?
# 0

ping -c 1 192.168.1.5 ; echo $?
# 2

Where

在哪里

0 means host reachable
>0 means unreachable

So, to test this in a bash script, you could do something like:

因此,要在 bash 脚本中对此进行测试,您可以执行以下操作:

ping -c1 -W1 -q $server &>/dev/null
status=$( echo $? )
if [[ $status == 0 ]] ; then
     #Connection success!
else
     #Connection failure
fi

回答by Ivo Varbanov

You can use the nc -z -G 2 SERVER_HOST PORTapproach with Ginstead of W. Gbeing used for timeout before connection established , so if host is unreachable , you'll know faster

您可以使用nc -z -G 2 SERVER_HOST PORT的方法有G代替WG用于在连接建立之前超时,因此如果主机无法访问,您会更快地知道

回答by Mike Q

Some more food for thought : Use nmap or nc, never ping.

一些更多的思考:使用 nmap 或 nc,永远不要 ping。

Ping:Why should you not use ping ? (1) It is better to check the system and the port at the same time. (2) Ping is unreliable as icmp echo is blocked in many situations.

Ping:你为什么不应该使用 ping ?(1) 最好同时检查系统和端口。(2) Ping 不可靠,因为在许多情况下 icmp echo 被阻塞。

Nmap:This is very quick, very reliable but requires nmap to be installed Preferred method NMAP (ex host ip 127.0.0.1) :

Nmap:这非常快,非常可靠,但需要安装 nmap 首选方法 NMAP(前主机 ip 127.0.0.1):

nmap 127.0.0.1 -PN -p ssh | grep open

Nc:nc is usually installed already , however on some systems such as Mac OS X, the command hangs on unreachable systems. (see workaround)

Nc:nc 通常已经安装,但是在某些系统(例如 Mac OS X)上,该命令在无法访问的系统上挂起。(见解决方法)

nc -v -z -w 3 127.0.0.1 22 &> /dev/null && echo "Online" || echo "Offline"

Mac OSX Workaround :

Mac OSX 解决方法:

bash -c '(sleep 3; kill $$) & exec nc -z 127.0.0.1 22' &> /dev/null
echo $?
0
bash -c '(sleep 3; kill $$) & exec nc -z 1.2.3.4 22' &> /dev/null
echo $?
143

(examples illustrate connecting to port 22 ssh over a good and bad host example, use the $? to determine if it reached the host with the sleep time of 3 seconds)

(示例说明通过一个好的和坏的主机示例连接到端口 22 ssh,使用 $? 确定它是否以 3 秒的睡眠时间到达主机)

For Mac Users (mainly) etc, you can use the command in the script like so :

对于 Mac 用户(主要是)等,您可以在脚本中使用命令,如下所示:

    # -- use NMAP, if not avail. go with nc --
    if command -v nmap | grep -iq nmap ; then
        nmap ${ip} -PN -p ${ssh_port} | grep -iq "open"
        res=$?
    elif command -v nc | grep -iq nc ; then
        # -- run command if fails to complete in 3 secs assume host unreachable --
        ( nc -z ${ip} ${ssh_port} ) & pid=$!
        ( sleep 3 && kill -HUP $pid ) 2>/dev/null & watcher=$!
        if wait $pid 2>/dev/null; then
            pkill -HUP -P $watcher
            wait $watcher
            # -- command finished (we have connection) --
            res=0
        else
            # -- command failed (no connection) --
            res=1
        fi
    else
        echo "Error: You must have NC or NMAP installed"
    fi

    if [[ ${res} -lt 1 ]] ;then
        success=1
        echo "testing  => $ip SUCCESS connection over port ${ssh_port}"
        break;
    else
        echo "testing => $ip FAILED connection over port ${ssh_port}"
    fi

回答by rocket singh

You can use below command,

您可以使用以下命令,

ping -c1 -W1 ip_addr || echo 'server is down'  

you can't use $ip_addr as it will remove first number of your IP.

你不能使用 $ip_addr 因为它会删除你的 IP 的第一个数字。