获取服务器运行状况的 Bash 脚本

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

Bash script to get server health

linuxbash

提问by Andrew Schleifer

Im looking to monitor some aspects of a farm of servers that are necessary for the application that runs on them.

我希望监视服务器群的某些方面,这些方面对于在其上运行的应用程序是必需的。

Basically, Im looking to have a file on each machine, which when accessed via http (on a vlan), with curl, that will spit out information Im looking for, which I can log into the database with dameon that sits in a loop and checks the health of all the servers one by one.

基本上,我希望在每台机器上都有一个文件,当通过 http(在 vlan 上)使用 curl 访问时,它将吐出我正在寻找的信息,我可以使用位于循环中的 dameon 登录到数据库中,一一检查所有服务器的健康状况。

The info Im looking to get is

我希望得到的信息是

<load>server load</load>
<free>md0 free space in MB</free>
<total>md0 total space in MB</total>
<processes># of nginx processes</processes>
<time>timestamp</time>

Whats the best way of doing that?

这样做的最佳方法是什么?

EDIT: We are using cacti and opennms, however what Im looking for here is data that is necessary for the application that runs on these servers. I dont want to complicate it by having it rely on any 3rd party software to fetch this basic data which can be gotten with a few linux commands.

编辑:我们正在使用 cacti 和 opennms,但是我在这里寻找的是在这些服务器上运行的应用程序所需的数据。我不想让它依赖任何 3rd 方软件来获取这个基本数据,这些数据可以通过一些 linux 命令获得,从而使它复杂化。

回答by Andrew Schleifer

Make a cron entry that:

创建一个 cron 条目:

  • executes a shell script every few minutes (or whatever frequency you want)
  • saves the output in a directory that's published by the web server
  • 每隔几分钟(或您想要的任何频率)执行一次 shell 脚本
  • 将输出保存在 Web 服务器发布的目录中

Assuming your text is literally what you want, this will get you 90% of the way there:

假设您的文本字面上是您想要的,这将使您达到 90%:

#!/usr/bin/env bash

LOAD=$(uptime | cut -d: -f5 | cut -d, -f1)
FREE=$(df -m / | tail -1 | awk '{ print  }')
TOTAL=$(df -m / | tail -1 | awk '{ print  }')
PROCESSES=$(ps aux | grep [n]ginx | wc -l)
TIME=$(date)

cat <<-EOF
<load>$LOAD</load>
<free>$FREE</free>
<total>$TOTAL</total>
<processes>$PROCESSES</processes>
<time>$TIME</time>
EOF

Sample output:

示例输出:

<load> 0.05</load>
<free>9988</free>
<total>13845</total>
<processes>6</processes>
<time>Wed Apr 18 22:14:35 CDT 2012</time>